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...
To avoid duplicating code, define common methods and attributes in a general class as a base:
public class Animal
{
public string Name { get; set; }
// Methods and attributes common to all animals
public void Eat(Object dinner)
{
// ...
}
public void Stare()...
An interface is used to enforce the presence of a method in any class that 'implements' it. The interface is defined with the keyword interface and a class can 'implement' it by adding : InterfaceName after the class name. A class can implement multiple interfaces by separating each interface with ...
public class Animal
{
public string Name { get; set; }
}
public interface INoiseMaker
{
string MakeNoise();
}
//Note that in C#, the base class name must come before the interface names
public class Cat : Animal, INoiseMaker
{
public Cat()
{
Name = "Ca...
public class Dog
{
private const string _birthStringFormat = "yyyy-MM-dd";
[XmlIgnore]
public DateTime Birth {get; set;}
[XmlElement(ElementName="Birth")]
public string BirthString
{
get { return Birth.ToString(_birthStringFormat); }
...
Code can and should throw exceptions in exceptional circumstances. Examples of this include:
Attempting to read past the end of a stream
Not having necessary permissions to access a file
Attempting to perform an invalid operation, such as dividing by zero
A timeout occurring when downloading a...
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...
public interface IAnimal
{
string Name { get; set; }
}
public interface INoiseMaker
{
string MakeNoise();
}
public class Cat : IAnimal, INoiseMaker
{
public Cat()
{
Name = "Cat";
}
public string Name { get; set; }
public string M...
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...
Immediately pass control to the next iteration of the enclosing loop construct (for, foreach, do, while):
for (var i = 0; i < 10; i++)
{
if (i < 5)
{
continue;
}
Console.WriteLine(i);
}
Output:
5
6
7
8
9
Live Demo on .NET Fiddle
var stuff = new [] ...
The using static [Namespace.Type] directive allows the importing of static members of types and enumeration values. Extension methods are imported as extension methods (from just one type), not into top-level scope.
6.0
using static System.Console;
using static System.ConsoleColor;
using static ...
To make a class support collection initializers, it must implement IEnumerable interface and have at least one Add method. Since C# 6, any collection implementing IEnumerable can be extended with custom Add methods using extension methods.
class Program
{
static void Main()
{
va...
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...
You are allowed to create and throw exceptions in your own code.
Instantiating an exception is done the same way that any other C# object.
Exception ex = new Exception();
// constructor with an overload that takes a message string
Exception ex = new Exception("Error message");
Yo...
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...