var numbers = new[] {1,2,3,4,5};
var firstNumber = numbers.First();
Console.WriteLine(firstNumber); //1
var firstEvenNumber = numbers.First(n => (n & 1) == 0);
Console.WriteLine(firstEvenNumber); //2
The following throws InvalidOperationException with message "Sequence contain...
var oneNumber = new[] {5};
var theOnlyNumber = oneNumber.SingleOrDefault();
Console.WriteLine(theOnlyNumber); //5
var numbers = new[] {1,2,3,4,5};
var theOnlyNumberSmallerThanTwo = numbers.SingleOrDefault(n => n < 2);
Console.WriteLine(theOnlyNumberSmallerThanTwo); //1
var theOnl...
For classes, interfaces, delegate, array, nullable (such as int?) and pointer types, default(TheType) returns null:
class MyClass {}
Debug.Assert(default(MyClass) == null);
Debug.Assert(default(string) == null);
For structs and enums, default(TheType) returns the same as new TheType():
struct...
The readonly keyword is a field modifier. When a field declaration includes a readonly modifier, assignments to that field can only occur as part of the declaration or in a constructor in the same class.
The readonly keyword is different from the const keyword. A const field can only be initialized...
Returns a new dictionary from the source IEnumerable using the provided keySelector function to determine keys. Will throw an ArgumentException if keySelector is not injective(returns a unique value for each member of the source collection.) There are overloads which allow one to specify the value t...
var numbers = new[] {2,4,6,8,1,3,5,7};
var numbersOrDefault = numbers.DefaultIfEmpty();
Console.WriteLine(numbers.SequenceEqual(numbersOrDefault)); //True
var noNumbers = new int[0];
var noNumbersOrDefault = noNumbers.DefaultIfEmpty();
Console.WriteLine(noNumbersOrDefault.Count()); //1
C...
Generating a new object in each step:
var elements = new[] {1,2,3,4,5};
var commaSeparatedElements = elements.Aggregate(
seed: "",
func: (aggregate, element) => $"{aggregate}{element},");
Console.WriteLine(commaSeparatedElements); //1,2,3,4,5,
Using th...
public class LivingBeing
{
string Name { get; set; }
}
public interface IAnimal
{
bool HasHair { get; set; }
}
public interface INoiseMaker
{
string MakeNoise();
}
//Note that in C#, the base class name must come before the interface names
public class Cat : LivingBei...
Overloading just equality operators is not enough. Under different circumstances, all of the following can be called:
object.Equals and object.GetHashCode
IEquatable<T>.Equals (optional, allows avoiding boxing)
operator == and operator != (optional, allows using operators)
When overrid...
try
{
/* code that could throw an exception */
}
catch (Exception ex)
{
/* handle the exception */
}
Note that handling all exceptions with the same code is often not the best approach.
This is commonly used when any inner exception handling routines fail, as a last resort.
try
{
/* code to open a file */
}
catch (System.IO.FileNotFoundException)
{
/* code to handle the file being not found */
}
catch (System.IO.UnauthorizedAccessException)
{
/* code to handle not being allowed access to the file */
}
catch (System.IO.IOException)
{
/* cod...
The ?. operator is syntactic sugar to avoid verbose null checks. It's also known as the Safe navigation operator.
Class used in the following example:
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
public Person Spouse { get; set; }
}
If a...
Similarly to the ?. operator, the null-conditional index operator checks for null values when indexing into a collection that may be null.
string item = collection?[index];
is syntactic sugar for
string item = null;
if(collection != null)
{
item = collection[index];
}
// assigning a signed short to its minimum value
short s = -32768;
// assigning a signed short to its maximum value
short s = 32767;
// assigning a signed int to its minimum value
int i = -2147483648;
// assigning a signed int to its maximum value
int i = 2147483647;
// assigning a s...