-
Putting
@
at the beginning of a variable name, allows to use a keyword.void Foo(int @string)
Implicitly typed variable
-
An implicitly typed variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type (i.e. the type of the constant). The following two declarations are equivalent:
var i = 10; // implicitly typed
int i = 10; //explicitly typed -
var
can be used for- local variables
-
a
for
initialization statement -
a
foreach
initialization statement -
a
using
statement
-
Arrays can also be implicitly typed. Jagged arrays are supported, but not multidimensional arrays.
var a = new[] { 1, 10, 100, 1000 };
var d = new[]
{
new[]{"Luca", "Mads", "Luke", "Dinesh"},
new[]{"Karen", "Suma", "Frances"}
};
Anonymous type
Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level.
var v = new { Amount = 108, Message = "Hello" }; |
Const
A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and null.
The constant declaration can declare multiple constants, such as:
public const double x = 1.0, y = 2.0, z = 3.0; |
static
modifier is not allowed in a constant declaration.)
Constructors
- Constructors have the same name as the class.
- A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated using the new operator and no arguments are provided to new.
- Unless the class is static, classes without constructors are given a public default constructor by the C# compiler in order to enable class instantiation.
- A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class. The declaration of the empty constructor prevents the automatic generation of a default constructor.
- Constructors for struct types are similar to class constructors, but structs cannot contain an explicit default constructor because one is provided automatically by the compiler. This constructor initializes each field in the struct to their default values. However, this default constructor is only invoked if the struct is instantiated with new.
-
Both classes and structs can define constructors that take parameters. Constructors that take parameters must be called through a new statement or a
base
statement. -
In a derived class, if a base class constructor is not called explicitly using the
base
keyword, then the default constructor, if there is one, is called implicitly. If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor usingbase
. -
A constructor can invoke another constructor in the same object using the
this
keyword. Likebase
,this
can be used with or without parameters, and any parameters in the constructor are available as parameters tothis
, or as part of an expression.public Employee(int weeklySalary, int numberOfWeeks)
: this(weeklySalary * numberOfWeeks)
{
}
Static Constructors
-
A constructor can be declared static using the
static
keyword. Static constructors are called automatically, immediately before any static fields are accessed, and are normally used to initialize static class members.class SampleClass
{
static SampleClass()
{
…
}
} - A static constructor does not take access modifiers or have parameters.
- A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
- A static constructor cannot be called directly.
- The user has no control on when the static constructor is executed in the program.
-
A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
Destructors
-
You cannot call or override the
Object.Finalize
method from the C# or C++ programming languages. C# uses destructors as the mechanism for writing finalization code. - Destructors cannot be defined in structs. They are only used with classes.
- A class can only have one destructor.
- Destructors cannot be inherited or overloaded.
- Destructors cannot be called. They are invoked automatically.
- A destructor does not take modifiers or have parameters.
- Destructors called recursively for all instances in the inheritance chain, from the most-derived to the least-derived.
- Empty destructors should not be used. When a class contains a destructor, an entry is created in the Finalize queue. When the destructor is called, the garbage collector is invoked to process the queue. If the destructor is empty, this just causes a needless loss of performance.
- If your application is using an expensive external resource, we also recommend that you provide a way to explicitly release the resource before the garbage collector frees the object. You do this by implementing a Dispose method from the IDisposable interface that performs the necessary cleanup for the object. This can considerably improve the performance of the application. Even with this explicit control over resources, the destructor becomes a safeguard to clean up resources if the call to the Dispose method failed.
Properties
private string name;
|
foobar.name = "AAA"
will call the setter
a = foobar.name
will call the getter
Auto-Implemented Properties
-
The compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
public double Name { get; set; }
-
For immutable classes, use
public string Name { get; private set; }
public string Address { get; private set; }public Contact2(string contactName, string contactAddress)
{
Name = contactName;
Address = contactAddress;
}private Contact(string contactName, string contactAddress)
{
Name = contactName;
Address = contactAddress;
}
public static Contact CreateContact(string name, string address)
{
new Contact(name, address);
}
Object initializer
-
Initialize the properties between curly brackets, separated by a comma
Cat cat = new Cat { Age = 10, Name = "Fluffy" };
-
This is particularly useful for anonymous types:
var productInfos =
from p in products
select new { p.ProductName, p.UnitPrice };select new {p.ProductName, Price = p.UnitPrice};
Collection Initializers
-
The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls.
List<int> digits = new List<int> { 0, 1, 2, 3, 0 + 1, 12 % 3, MakeInt() };
Readonly
The
readonly
keyword is a modifier that you can use on fields: assignments to the fields 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 at the declaration of the field. A readonly
field can be initialized either at the declaration or in a constructor. Therefore, readonly
fields can have different values depending on the constructor used. Also, while a const
field is a compile-time constant, the readonly
field can be used for run-time constants, as in this line:
public static readonly uint l1 = (uint)DateTime.Now.Ticks; |
String literals
-
regular string literal: "string"
\
must be followed by one of the following characters:'
,"
,\
,0
,a
,b
,f
,n
,r
,t
,u
,U
,x
,v
the string literal "\x123" contains a single character with hex value 123. To create a string containing the character with hex value 12 followed by the character 3, you could write "\x00123" or "\x12" + "3" instead. -
use the
\u
prefix for Unicode characters, e.g.f
is\u0066
. -
verbatim string literal:
@"string"
all characters are interpreted verbatim, except the quote escape sequence (i.e.""
to insert a"
)
Array constants
-
int[] entiers = new int[] {0,10,20,30};
-
double[,] réels = new double[,] { {0.5, 1.7}, {8.4, -6}};
-
double[,] réels = { {0.5, 1.7}, {8.4, -6}};
Delegates
- A delegate is a type that defines a method signature. When you instantiate a delegate, you can associate its instance with any method with a compatible signature. You can invoke (or call) the method through the delegate instance. Delegates are used to pass methods as arguments to other methods.
-
History
-
delegate void TestDelegate(string s);
-
C# 1.0, an instance of a delegate is explicitly initialized with a method that was defined elsewhere in the code.
static void M(string s)
{
Console.WriteLine(s);
}
…
TestDelegate testDelA = new TestDelegate(M);TestDelegate testDelA = M;
-
C# 2.0 introduced anonymous methods as a way to write unnamed inline statement blocks that can be executed in a delegate invocation.
TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };
-
C# 3.0 introduced lambda expressions, which are similar in concept to anonymous methods but more expressive and concise.
TestDelegate testDelC = (x) => { Console.WriteLine(x); };
- Anonymous methods and lambda expressions are both known as "anonymous functions".
-
- Delegates constructed with a named method can encapsulate either a static method or an instance method.
- Delegate types are sealed, they cannot be derived from.
- After a delegate is created, the method it is associated with never changes; delegate objects are immutable.
- When a delegate is constructed to wrap an instance method, the delegate references both the instance and the method. A delegate has no knowledge of the instance type aside from the method it wraps, so a delegate can refer to any type of object as long as there is a method on that object that matches the delegate signature.
-
Multicasting
-
To add an extra method to the delegate’s list of methods - the invocation list - simply requires adding two delegates using the addition or addition assignment operators ('+' or '+=').
MethodClass obj = new MethodClass();
Del d1 = obj.Method1;
Del d2 = obj.Method2;
Del d3 = DelegateMethod;
Del allMethodsDelegate = d1 + d2;
allMethodsDelegate += d3; -
To remove a method from the invocation list, use the decrement or decrement assignment operator ('-' or '-=').
//remove Method1
allMethodsDelegate -= d1;
// copy AllMethodsDelegate while removing d2
Del oneMethodDelegate = allMethodsDelegate - d2; -
Because delegate types are derived from System.Delegate, the methods and properties defined by that class can be called on the delegate. For example, to find the number of methods in a delegate’s invocation list:
int invocationCount = d1.GetInvocationList().GetLength(0);
-
Delegates with more than one method in their invocation list derive from
System.MulticastDelegate
, which is a subclass ofSystem.Delegate
.
-
To add an extra method to the delegate’s list of methods - the invocation list - simply requires adding two delegates using the addition or addition assignment operators ('+' or '+=').
Anonymous methods
- There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions.
-
The local variables and parameters whose scope contains an anonymous method declaration are called outer variables of the anonymous method. For example, in the following code segment, n is an outer variable:
int n = 0;
Del d = delegate() { System.Console.WriteLine("Copy #:{0}", ++n); }; - An anonymous method cannot access the ref or out parameters of an outer scope.
- No unsafe code can be accessed within the anonymous-method-block.
-
Anonymous methods are not allowed on the left side of the
is
operator.
Lambda expressions
-
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. All lambda expressions use the lambda operator
=>
, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. -
The
=>
operator has the same precedence as assignment (=
) and is right-associative. -
Lambdas are not allowed on the left side of the
is
oras
operator. -
A lambda expression with an expression on the right side is called an expression lambda.
(input parameters) => expression
(x, y) => x == y
(int x, string s) => s.Length > x
() => SomeMethod()
-
A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces:
(input parameters) => {statement;}
Statement lambdas, like anonymous methods, cannot be used to create expression trees.
The return value must be withreturn
.
(int x, string s) => s.Length > x
(int x, string s) => { return (s.Length > x);}
-
Type Inference in Lambdas
When writing lambdas, you often do not have to specify a type for the input parameters because the compiler can infer the type based on the lambda body, the underlying delegate type, and other factors.- The lambda must contain the same number of parameters as the delegate type.
- Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter.
- The return value of the lambda (if any) must be implicitly convertible to the delegate’s return type.
-
Variable Scope in Lambda Expressions
Lambdas can refer to outer variables that are in scope in the enclosing method or type in which the lambda is defined. Variables that are captured in this manner are stored for use in the lambda expression even if variables would otherwise go out of scope and be garbage collected.- A variable that is captured will not be garbage-collected until the delegate that references it goes out of scope.
- Variables introduced within a lambda expression are not visible in the outer method.
- A lambda expression cannot directly capture a ref or out parameter from an enclosing method.
- A return statement in a lambda expression does not cause the enclosing method to return.
- A lambda expression cannot contain a goto statement, break statement, or continue statement whose target is outside the body or in the body of a contained anonymous function.
Nullable Types
Nullable types are instances of the
System.Nullable struct
. A nullable type can represent the normal range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32>
, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool>
can be assigned the values true or false, or null.
Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)
The syntax
T?
is shorthand for System.Nullable<T>
, where T
is a value type. The two forms are interchangeable.
Use the
System.Nullable.GetValueOrDefault
property to return either the assigned value, or the default value for the underlying type if the value is null.
Use the
HasValue
and Value
read-only properties to test for null and retrieve the value. The HasValue
property returns true if the variable contains a value, or false if it is null. The Value
property returns a value if one is assigned, otherwise a System.InvalidOperationException
is thrown.
The default value for a nullable type variable sets
HasValue
to false. The Value
is undefined.
Use the
??
(the null-coalescing operator) operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type
int? x = null; int y = x ?? -1; |
Argument by reference
In order to pass argument by reference, use the
ref
or out
both in the method definition and the method call
int i=1;
|
ref
, the variable must be initialized before.
With
out
, the variable may not be initialized before.
Access modifiers
-
public
The type or member can be accessed by any other code in the same assembly or another assembly that references it. -
private
The type or member can be accessed only by code in the same class or struct. -
protected
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class. -
internal
The type or member can be accessed by any code in the same assembly, but not from another assembly. -
protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.
Abstract class and abstract class member
-
An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
public abstract class foo {}
-
Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods.
public abstract class foo
{
public abstract void DoWork(int i);
} -
When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method.
public class D
{
public virtual void DoWork(int i)
{
// Original implementation
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation
}
}DoWork
on class F cannot callDoWork
on class D. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.
Sealed class and sealed class member
-
When applied to a class, the sealed modifier prevents other classes from inheriting from it.
public sealed class foo {}
-
A class member, method, field, property, or event can also be
sealed
. This allows classes to derive from the class while preventing them from overriding specific virtual methods or properties.public class foo : bar { public sealed override void DoWork() { } }
Partial class definition
It is possible to split the definition of a class or a struct, or an interface over two or more source files. Each source file contains a section of the class definition, and all parts are combined when the application is compiled.
public partial class Employee
|
Deriving a class
class TestBase
|
Overriding a method
class TestBase
|
Base
The base keyword is used to access members of the base class from within a derived class:
- Call a method on the base class that has been overridden by another method.
- Specify which base-class constructor should be called when creating instances of the derived class.
Extension methods
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
namespace ExtensionMethods
|
using ExtensionMethods;
|
Variable number of parameters
static void Main()
|
Object[]
.
Unsafe code
The
unsafe
keyword denotes an unsafe context, which is required for any operation involving pointers.
You can use the unsafe modifier in the declaration of a type, a member, or a code block.
yield
Used in an iterator block to provide a value to the enumerator object or to signal the end of iteration. It takes one of the following forms:
yield return <expression>; |
yield break; |
throw
The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution. It takes the following form
throw [expression];
, where expression
is the exception object. This is omitted when rethrowing the current exception object in a catch clause.
try-catch-finally
A common usage of
catch
and finally
together is to obtain and use resources in a try
block, deal with exceptional circumstances in a catch
block, and release the resources in the finally
block.
using System;
|
using
Defines a scope, outside of which an object or objects will be disposed.
using (Font font = new Font("Arial", 10.0f))
|
Font font = new Font("Arial", 10.0f);
|
using (Font font3 = new Font("Arial", 10.0f),
|
Unit tests
-
Attributes
TestClassAttribute
used to tag a class has containing test methods TestMethodAttribute
used to tag a test method ExpectedExceptionAttribute
used to indicate that a test method expects an exception
example:[ExpectedException(typeof(System.DivideByZeroException))]
OwnerAttribute
define the test owner DescriptionAttribute
describe the test TestPropertyAttribute
add a name-value pair AssemblyInitializeAttribute
identify the method to be executed before running all the test of an assembly AssemblyCleanupAttribute
identify the method to be executed after running all the test of an assembly ClassInitializeAttribute
identify the method to be executed before running all the tests of a test class (only one method in a class may be decorated with this attribute) ClassCleanupAttribute
identify the method to be executed before running all the tests of a test class (only one method in a class may be decorated with this attribute) TestInitializeAttribute
identify the method to be executed before running every test of a test class TestCleanupAttribute
identify the method to be executed after running every test of a test class DataSourceAttribute
define the source for test data (e.g. a SQL table)
The order of execution is
1 Methods marked with the AssemblyInitializeAttribute
2 Methods marked with the ClassInitializeAttribute
3 Methods marked with the TestInitializeAttribute
4 Methods marked with the TestMethodAttribute
5 Methods marked with the TestCleanupAttribute
6 Methods marked with the ClassCleanupAttribute
7 Methods marked with the AssemblyCleanupAttribute
-
methods of
Assert
Inconclusive()
Inconclusive(String)
Inconclusive(String, Object[])
the assertion cannot be verified AreEqual(Object, Object)
AreEqual<T>(Object, Object)
AreEqual(Object, Object, String)
AreEqual<T>(Object, Object, String)
AreEqual(Object, Object, String, Object[])
AreEqual<T>(Object, Object, String, Object[])
verify that two values are equal by using the equality operator AreEqual(Single, Single, Single)
AreEqual(Single, Single, Single, String)
AreEqual(Single, Single, Single, String, Object[])
verify that two specified singles are equal, or within the specified accuracy of each other AreEqual(Double, Double, Double)
AreEqual(Double, Double, Double, String)
AreEqual(Double, Double, Double, String, Object[])
verify that two specified doubles are equal, or within the specified accuracy of each other IsTrue(Boolean)
IsTrue(Boolean, String)
IsFalse(Boolean, String, Object[])
verify that the specified condition is true IsFalse(Boolean)
IsFalse(Boolean, String)
IsFalse(Boolean, String, Object[])
verify that the specified condition is true IsNull(Object)
IsNull(Object, String)
IsNull(Object, String, Object[])
verify that the specified object is null IsNotNull(Object)
IsNotNull(Object, String)
IsNotNull(Object, String, Object[])
verify that the specified object is not null
Exception
-
System.ArgumentException
thrown when one of the arguments provided to a method is not valid System.ArgumentNullException
thrown when a null reference is passed to a method that does not accept it as a valid argument System.NotImplementedException
thrown when a requested method or operation is not implemented
Collections
-
All of them have the following basic methods and properties to manipulate the stored data:
Add
add a new element Remove
remove an existing element Count
get the total number of elements stored in a collection -
Non-Generic Collections
Found under theSystem.Collections
namespace.ArrayList
an array of contiguous indexed elements whose size can be increased dynamically at run time as required BitArray
an array of contiguous bit values (zeros and ones). Its size must be determined at design time SortedList
a list of key/value pair elements, sorted by keys and can be accessed by key and by index Stack
a LIFO data structure Queue
a FIFO data structure HashTable
a collection of key/value pair elements stored based on the hash code of the key -
Generic Collections
Found under theSystem.Collections.Generic
namespace.HashSet
a set of values SortedSet
a collection of objects that is maintained in sorted order LinkedList
linked list data structure Dictionary
set of key/value pair elements List
same as ArrayList Queue
same as Queue Stack
same as Stack
Predefined delegates (member of
System
)
-
public delegate TResult Func<out TResult>()
-
public delegate TResult Func<in T,out TResult>(T arg)
-
public delegate TResult Func<in T1,in T2,out TResult>(T1 arg1, T2 arg2)
- …
-
public delegate TResult Func<in T1,in T2,in T3,in T4,in T5,in T6,in T7,in T8,in T9,in T10,in T11,in T12,in T13,in T14,in T15,in T16,out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16)
-
public delegate void Action()
-
public delegate void Action<in T>(T obj)
-
public delegate void Action<in T1,in T2>(T1 arg1, T2 arg2)
- …
-
public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6,in T7,in T8,in T9,in T10,in T11,in T12,in T13,in T14,in T15,in T16>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16)
Linq
-
Enumerable Methods
public static bool Any<TSource>(this IEnumerable<TSource> source)
determines whether a sequence contains any elements public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
determines whether any element of a sequence satisfies a predicate public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
determines whether all elements of a sequence satisfy a predicate public static TSource First<TSource>(this IEnumerable<TSource> source)
return the first element
throwsInvalidOperationException
if the Enumerable is emptypublic static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
return the first element that satisfies a predicate
throwsInvalidOperationException
if the Enumerable is empty or if no element satisfies the predicatepublic static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source)
return the first element
returns the default value if the Enumerable is emptypublic static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
return the first element that satisfies a predicate
returns the default value if the Enumerable is empty or if no element satisfies the predicatepublic static TSource Last<TSource>(this IEnumerable<TSource> source)
return the last element
throwsInvalidOperationException
if the Enumerable is emptypublic static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
return the last element that satisfies a predicate
throwsInvalidOperationException
if the Enumerable is empty or if no element satisfies the predicatepublic static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source)
return the last element
returns the default value if the Enumerable is emptypublic static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
return the last element that satisfies a predicate
returns the default value if the Enumerable is empty or if no element satisfies the predicatepublic static int Count<TSource>(this IEnumerable<TSource> source)
returns the number of elements in a sequence public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
returns a number that represents how many elements in the specified sequence satisfy a predicate public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
filters a sequence of values based on a predicate public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)
filters a sequence of values based on a predicate using the element’s index public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source)
filters the elements of a sequence based on a specified type public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
sorts the elements of a sequence in ascending order according to a key public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
sorts the elements of a sequence in ascending order by using a specified comparer public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
sorts the elements of a sequence in descending order according to a key public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
sorts the elements of a sequence in descending order by using a specified comparer public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
performs a subsequent ordering of the elements of a sequence in ascending order according to a key public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
performs a subsequent ordering of the elements of a sequence in ascending order by using a specified comparer public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
performs a subsequent ordering of the elements of a sequence in descending order according to a key public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
performs a subsequent ordering of the elements of a sequence in descending order by using a specified comparer public static IEnumerable<TResult> Select<TSource, Tresult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
applies a function to each element of the Enumerable and returns the corresponding Enumerable public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector)
applies a function to each element, using its index, of the Enumerable and returns the corresponding Enumerable public static IEnumerable<TResult> SelectMany<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TResult>> selector)
applies a function returning an Enumerable to each element of the Enumerable and return the flatten Enumerable public static IEnumerable<TResult> SelectMany<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, IEnumerable<TResult>> selector)
applies a function returning an Enumerable to each element, using its index, of the Enumerable and return the flatten Enumerable public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this IEnumerable<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)
applies a function returning an Enumerable to each element of the Enumerable, build the flatten Enumerable, and applies a function on each couple (element of the initial Enumerable, element of that element’s Enumerable public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this IEnumerable<TSource> source, Func<TSource, int, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)
applies a function returning an Enumerable to each element, using its index, of the Enumerable, build the flatten Enumerable, and applies a function on each couple (element of the initial Enumerable, element of that element’s Enumerable public static TSource Aggregate<TSource>(this IEnumerable<TSource> source, Func<TSource, TSource, TSource> func)
applies an accumulator function over a sequence
This method works by callingfunc
one time for each element insource
except the first one. Each timefunc
is called,Aggregate
passes both the element from the sequence and an aggregated value (as the first argument tofunc
). The first element ofsource
is used as the initial aggregate value. The result offunc
replaces the previous aggregated value.Aggregate
returns the final result offunc
.
Code contracs
-
PureAttribute
indicates that a method is pure.
checked
/unchecked
-
unchecked
suppresses overflow-checking for integral-type arithmetic operations and conversions.try
{
z = checked((short)(x + y));
}
catch (System.OverflowException e)
{
Console.WriteLine(e.ToString());
} -
checked
explicitly enables overflow-checking for integral-type arithmetic operations and conversions.unchecked
{
z = x * y;
} -
If neither
checked
norunchecked
is specified, the default context depends on external factors such as compiler options.