Tutorial by Examples: a

By using the new() constraint, it is possible to enforce type parameters to define an empty (default) constructor. class Foo { public Foo () { } } class Bar { public Bar (string s) { ... } } class Factory<T> where T : new() { public T Create() { re...
Every method has a unique signature consisting of a accessor (public, private, ...) ,optional modifier (abstract), a name and if needed method parameters. Note, that the return type is not part of the signature. A method prototype looks like the following: AccessModifier OptionalModifier ReturnTyp...
Calling a static method: // Single argument System.Console.WriteLine("Hello World"); // Multiple arguments string name = "User"; System.Console.WriteLine("Hello, {0}!", name); Calling a static method and storing its return value: string input = System.Con...
A method can declare any number of parameters (in this example, i, s and o are the parameters): static void DoSomething(int i, string s, object o) { Console.WriteLine(String.Format("i={0}, s={1}, o={2}", i, s, o)); } Parameters can be used to pass values into a method, so that th...
You can use default parameters if you want to provide the option to leave out parameters: static void SaySomething(string what = "ehh") { Console.WriteLine(what); } static void Main() { // prints "hello" SaySomething("hello"); // prints &quot...
The yield keyword is used to define a function which returns an IEnumerable or IEnumerator (as well as their derived generic variants) whose values are generated lazily as a caller iterates over the returned collection. Read more about the purpose in the remarks section. The following example has a...
public IEnumerable<User> SelectUsers() { // Execute an SQL query on a database. using (IDataReader reader = this.Database.ExecuteReader(CommandType.Text, "SELECT Id, Name FROM Users")) { while (reader.Read()) { int id = reader.GetInt32(0...
You can extend the functionality of existing yield methods by passing in one or more values or elements that could define a terminating condition within the function by calling a yield break to stop the inner loop from executing. public static IEnumerable<int> CountUntilAny(int start, HashSet...
using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.Composition; namespace Demo { [Export(typeof(IUserProvider))] public sealed class UserProvider : IUserProvider { public ReadOnlyCollection<User> GetAllUsers() ...
using System; using System.ComponentModel.Composition; namespace Demo { public sealed class UserWriter { [Import(typeof(IUserProvider))] private IUserProvider userProvider; public void PrintAllUsers() { foreach (User user in this.user...
See the other (Basic) examples above. using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; namespace Demo { public static class Program { public static void Main() { using (var catalog = new ApplicationCatalog()) ...
class Program { static void Main(string[] args) { // Run 2 Tasks. var task1 = Task.Run(() => PerformAction(1))); var task2 = Task.Run(() => PerformAction(2))); // Wait (i.e. block this thread) until both Tasks are complete. Task.WaitA...
6.0 As of C# 6.0, the await keyword can now be used within a catch and finally block. try { var client = new AsyncClient(); await client.DoSomething(); } catch (MyException ex) { await client.LogExceptionAsync(); throw; } finally { await client.CloseAsync(); } 5.06.0 P...
1 - Create an empty folder, it will contain the files created in the next steps. 2 - Create a file named project.json with the following content (adjust the port number and rootDirectory as appropriate): { "dependencies": { "Microsoft.AspNet.Server.Kestrel": "1.0.0...
Developers can be caught out by the fact that type inference doesn't work for constructors: class Tuple<T1,T2> { public Tuple(T1 value1, T2 value2) { } } var x = new Tuple(2, "two"); // This WON'T work... var y = new Tuple<int, string>(2, "t...
Typically lambdas are used for defining simple functions (generally in the context of a linq expression): var incremented = myEnumerable.Select(x => x + 1); Here the return is implicit. However, it is also possible to pass actions as lambdas: myObservable.Do(x => Console.WriteLine(x)); ...
An iterator method is not executed until the return value is enumerated. It's therefore advantageous to assert preconditions outside of the iterator. public static IEnumerable<int> Count(int start, int count) { // The exception will throw when the method is called, not when the result i...
Use parentheses around the expression to the left of the => operator to indicate multiple parameters. delegate int ModifyInt(int input1, int input2); ModifyInt multiplyTwoInts = (x,y) => x * y; Similarly, an empty set of parentheses indicates that the function does not accept parameters. ...
Unlike an expression lambda, a statement lambda can contain multiple statements separated by semicolons. delegate void ModifyInt(int input); ModifyInt addOneAndTellMe = x => { int result = x + 1; Console.WriteLine(result); }; Note that the statements are enclosed in braces {}. ...
For null values: Nullable<int> i = null; Or: int? i = null; Or: var i = (int?)null; For non-null values: Nullable<int> i = 0; Or: int? i = 0;

Page 9 of 1099