Tutorial by Examples: a

C# allows user-defined types to overload operators by defining static member functions using the operator keyword. The following example illustrates an implementation of the + operator. If we have a Complex class which represents a complex number: public struct Complex { public double Real ...
Extension methods can also be used like ordinary static class methods. This way of calling an extension method is more verbose, but is necessary in some cases. static class StringExtensions { public static string Shorten(this string text, int length) { return text.Substring(0, ...
Initialize a collection type with values: var stringList = new List<string> { "foo", "bar", }; Collection initializers are syntactic sugar for Add() calls. Above code is equivalent to: var temp = new List<string>(); temp.Add("foo"); temp.A...
Equals Checks whether the supplied operands (arguments) are equal "a" == "b" // Returns false. "a" == "a" // Returns true. 1 == 0 // Returns false. 1 == 1 // Returns true. false == true // Returns false. false == false // Return...
var date = new DateTime(2015, 11, 11); var str = $"It's {date:MMMM d, yyyy}, make a wish!"; System.Console.WriteLine(str); You can also use the DateTime.ToString method to format the DateTime object. This will produce the same output as the code above. var date = new DateTime(2015, 1...
Double Quotes inside verbatim strings can be escaped by using 2 sequential double quotes "" to represent one double quote " in the resulting string. var str = @"""I don't think so,"" he said."; Console.WriteLine(str); Output: "I don't think s...
Verbatim strings can be combined with the new String interpolation features found in C#6. Console.WriteLine($@"Testing \n 1 2 {5 - 2} New line"); Output: Testing \n 1 2 3 New line Live Demo on .NET Fiddle As expected from a verbatim string, the backslashes are ignored as escap...
The nameof operator returns the name of a code element as a string. This is useful when throwing exceptions related to method arguments and also when implementing INotifyPropertyChanged. public string SayHello(string greeted) { if (greeted == null) throw new ArgumentNullException(nam...
Introduction Properties can be initialized with the = operator after the closing }. The Coordinate class below shows the available options for initializing a property: 6.0 public class Coordinate { public int X { get; set; } = 34; // get or set auto-property with initializer public ...
Index initializers make it possible to create and initialize objects with indexes at the same time. This makes initializing Dictionaries very easy: var dict = new Dictionary<string, int>() { ["foo"] = 34, ["bar"] = 42 }; Any object that has an indexed gette...
String interpolation allows the developer to combine variables and text to form a string. Basic Example Two int variables are created: foo and bar. int foo = 34; int bar = 42; string resultString = $"The foo is {foo}, and the bar is {bar}."; Console.WriteLine(resultString); ...
It is possible to use await expression to apply await operator to Tasks or Task(Of TResult) in the catch and finally blocks in C#6. It was not possible to use the await expression in the catch and finally blocks in earlier versions due to compiler limitations. C#6 makes awaiting async tasks a lot e...
The ?. operator and ?[...] operator are called the null-conditional operator. It is also sometimes referred to by other names such as the safe navigation operator. This is useful, because if the . (member accessor) operator is applied to an expression that evaluates to null, the program will throw ...
By definition, the short-circuiting boolean operators will only evaluate the second operand if the first operand can not determine the overall result of the expression. It means that, if you are using && operator as firstCondition && secondCondition it will evaluate secondCondition ...
Starting with C# 6, collections with indexers can be initialized by specifying the index to assign in square brackets, followed by an equals sign, followed by the value to assign. Dictionary Initialization An example of this syntax using a Dictionary: var dict = new Dictionary<string, int> ...
When a type is defined without a constructor: public class Animal { } then the compiler generates a default constructor equivalent to the following: public class Animal { public Animal() {} } The definition of any constructor for the type will suppress the default constructor genera...
public class Animal { public string Name { get; set; } public Animal() : this("Dog") { } public Animal(string name) { Name = name; } } var dog = new Animal(); // dog.Name will be set to "Dog" by default. var cat = new Ani...
The stackalloc keyword creates a region of memory on the stack and returns a pointer to the start of that memory. Stack allocated memory is automatically removed when the scope it was created in is exited. //Allocate 1024 bytes. This returns a pointer to the first byte. byte* ptr = stackalloc byte...
Adding the volatile keyword to a field indicates to the compiler that the field's value may be changed by multiple separate threads. The primary purpose of the volatile keyword is to prevent compiler optimizations that assume only single-threaded access. Using volatile ensures that the value of the ...
A static constructor is called the first time any member of a type is initialized, a static class member is called or a static method. The static constructor is thread safe. A static constructor is commonly used to: Initialize static state, that is state which is shared across different instan...

Page 2 of 1099