C# Reference

C# Keywords

Keywords are predefined, reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if is a valid identifier but if is not because if is a keyword.

The first table in this topic lists keywords that are reserved identifiers in any part of a C# program. The second table in this topic lists the contextual keywords in C#. Contextual keywords have special meaning only in a limited program context and can be used as identifiers outside that context. Generally, as new keywords are added to the C# language, they are added as contextual keywords in order to avoid breaking programs written in earlier versions.

So here we goes to quickly review your C# skills. you may click on links to dig more into keywords implementation on msdn. press back button to continue from msdn.

Keywords Description
abstract The abstract modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class.
as The as operator is used to perform certain types of conversions between compatible reference types.
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.

A base class access is permitted only in a constructor, an instance method, or an instance property accessor.

It is an error to use the base keyword from within a static method.

The base class that is accessed is the base class specified in the class declaration. For example, if you specify class ClassB : ClassA, the members of ClassA are accessed from ClassB, regardless of the base class of ClassA.

bool The bool keyword is an alias of System.Boolean. It is used to declare variables to store the Boolean values, true and false.If you require a Boolean variable that can also have a value of null, use bool? For more information, see Nullable Types (C# Programming Guide).
break The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement, if any.
byte The byte keyword denotes an integral type that stores values (0 to 255) as Unsigned 8-bit integer
case The switch statement is a control statement that selects a switch section to execute from a list of candidates.Each switch section contains one or more case labels and a list of one or more statements.
catch The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions. When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.
char The char keyword is used to declare a Unicode character in the range U+0000 to U+ffff. Unicode characters are 16-bit characters that are used to represent most of the known written languages throughout the world.
checked The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.By default, an expression that contains only constant values causes a compiler error if the expression produces a value that is outside the range of the destination type. If the expression contains one or more non-constant values, the compiler does not detect the overflow.By default, the non-constant expressions are not checked for overflow at run time either, and they do not raise overflow exceptions. Overflow checking can be enabled by compiler options, environment configuration, or use of the checked keyword.// Checked expression.Console.WriteLine(checked(2147483647 + ten));
class Classes are declared using the keyword class. Unlike C++, only single inheritance is allowed in C#. In other words, a class can inherit implementation from one base class only. However, a class can implement more than one interface (multiple interface inheritance). The access levels protected and private are only allowed on nested classes. You can also declare generic classes that have type parameters; see Generic Classes for more information.A class can contain declarations of the following members:

Constructors Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read.If you do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values as listed in Default Values Table (C# Reference). Static classes and structs can also have constructors.
Destructors Destructors are used to destruct instances of classes.

  • 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.
Constants Constants are immutable values which are known at compile time and do not change for the life of the program. Constants are declared with the const modifier. Only the C# built-in types (excluding System.Object) may be declared as const. For a list of the built-in types, see Built-In Types Table (C# Reference). User-defined types, including classes, structs, and arrays, cannot be const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed.Constants must be initialized as they are declared.
Fields A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type.A class or struct may have instance fields or static fields or both. Instance fields are specific to an instance of a type. If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object. By contrast, a static field belongs to the class itself, and is shared among all instances of that class. Changes made from instance A will be visibly immediately to instances B and C if they access the field.Generally, you should use fields only for variables that have private or protected accessibility. Data that your class exposes to client code should be provided through methods, properties and indexers. By using these constructs for indirect access to internal fields, you can guard against invalid input values. A private field that stores the data exposed by a public property is called a backing store or backing field.Fields typically store the data that must be accessible to more than one class method and must be stored for longer than the lifetime of any single method. For example, a class that represents a calendar date might have three integer fields: one for the month, one for the day, and one for the year. Variables that are not used outside the scope of a single method should be declared as local variables within the method body itself.Fields are declared in the class block by specifying the access level of the field, followed by the type of the field
Methods A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method and specifying any required method arguments. In C#, every executed instruction is performed in the context of a method. The Main method is the entry point for every C# application and it is called by the common language runtime (CLR) when the program is started.Methods are declared in a class or struct by specifying the access level such as public or private, optional modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters. These parts together are the signature of the method.A return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to.By default, when a value type is passed to a method, a copy is passed instead of the object itself. Therefore, changes to the argument have no effect on the original copy in the calling method. You can pass a value-type by reference by using the ref keyword.Reference types are passed by reference. When an object of a reference type is passed to a method, the reference points to the original object, not a copy. Changes made through this reference will therefore be reflected in the calling method.Methods can return a value to the caller. If the return type, the type listed before the method name, is not void, the method can return the value by using the return keyword. A statement with the return keyword followed by a value that matches the return type will return that value to the method caller. The return keyword also stops the execution of the method. If the return type is void, a return statement without a value is still useful to stop the execution of the method. Without the return keyword, the method will stop executing when it reaches the end of the code block. Methods with a non-void return type are required to use the return keyword to return a value.
Properties Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
Indexers Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.
Operators In C#, an operator is a program element that is applied to one or more operands in an expression or statement. Operators that take one operand, such as the increment operator (++) or new, are referred to as unary operators. Operators that take two operands, such as arithmetic operators (+,-,*,/), are referred to as binary operators. One operator, the conditional operator (?:), takes three operands and is the sole ternary operator in C#.
Events Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.Events have the following properties:

  • The publisher determines when an event is raised; the subscribers determine what action is taken in response to the event.
  • An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.
  • Events that have no subscribers are never raised.
  • Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces.
  • When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised. To invoke events asynchronously, see Calling Synchronous Methods Asynchronously.
  • Events can be used to synchronize threads.
  • In the .NET Framework class library, events are based on the EventHandler delegate and the EventArgs base class.
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. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method and a class such as a windows control can call your method when a certain event occurs.Any method from any accessible class or struct that matches the delegate’s signature, which consists of the return type and parameters, can be assigned to the delegate. The method can be either static or an instance method. This makes it possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the signature of the delegate, you can assign your own method.In the context of method overloading, the signature of a method does not include the return value. But in the context of delegates, the signature does include the return value. In other words, a method must have the same return value as the delegate.Delegates have the following properties:

  • Delegates are like C++ function pointers but are type safe.
  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.
  • Methods do not have to match the delegate signature exactly. For more information, see Using Variance in Delegates (C# and Visual Basic).
  • C# version 2.0 introduced the concept of Anonymous Methods, which allow code blocks to be passed as parameters in place of a separately defined method. C# 3.0 introduced lambda expressions as a more concise way of writing inline code blocks. Both anonymous methods and lambda expressions (in certain contexts) are compiled to delegate types. Together, these features are now known as anonymous functions. For more information about lambda expressions, see Anonymous Functions (C# Programming Guide).
Classes A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable.
Interfaces Interfaces describe a group of related functionalities that can belong to any class or struct. Interfaces can consist of methods, properties, events, indexers, or any combination of those four member types. An interface cannot contain fields. Interfaces members are automatically public.When a class or struct is said to inherit an interface, it means that the class or struct provides an implementation for all of the members defined by the interface. The interface itself provides no functionality that a class or struct can inherit in the way that base class functionality can be inherited. However, if a base class implements an interface, the derived class inherits that implementation.Classes and structs can inherit from interfaces in a manner similar to how classes can inherit a base class or struct, with two exceptions:

  • A class or struct can inherit more than one interface.
  • When a class or struct inherits an interface, it inherits only the method names and signatures, because the interface itself contains no implementations.

To implement an interface member, the corresponding member on the class must be public, non-static, and have the same name and signature as the interface member. Properties and indexers on a class can define extra accessors for a property or indexer defined on an interface. For example, an interface may declare a property with a get accessor, but the class implementing the interface can declare the same property with both a get and set accessor. However, if the property or indexer uses explicit implementation, the accessors must match.

Interfaces and interface members are abstract; interfaces do not provide a default implementation.

The IEquatable<T> interface announces to the user of the object that the object can determine whether it is equal to other objects of the same type, and the user of the interface does not have to know how this is implemented.

Interfaces can inherit other interfaces. It is possible for a class to inherit an interface multiple times, through base classes or interfaces it inherits. In this case, the class can only implement the interface one time, if it is declared as part of the new class. If the inherited interface is not declared as part of the new class, its implementation is provided by the base class that declared it. It is possible for a base class to implement interface members using virtual members; in that case, the class inheriting the interface can change the interface behavior by overriding the virtual members. For more information about virtual members, see Polymorphism.

An interface has the following properties:

  • An interface is like an abstract base class: any non-abstract type inheriting the interface must implement all its members.
  • An interface cannot be instantiated directly.
  • Interfaces can contain events, indexers, methods and properties.
  • Interfaces contain no implementation of methods.
  • Classes and structs can inherit from more than one interface.
  • An interface can itself inherit from multiple interfaces.
Structs Structs share most of the same syntax as classes, although structs are more limited than classes:

  • Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
  • A struct may not declare a default constructor (a constructor without parameters) or a destructor.
  • Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. This is important to remember when working with collections of value types such as Dictionary<string, myStruct>.
  • Structs are value types and classes are reference types.
  • Unlike classes, structs can be instantiated without using a new operator.
  • Structs can declare constructors that have parameters.
  • A struct cannot inherit from another struct or class, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object.
  • A struct can implement interfaces.
  • A struct can be used as a nullable type and can be assigned a null value.
const The const keyword is used to modify a declaration of a field or local variable. It specifies that the value of the field or the local variable is constant, which means it cannot be modified.The readonly keyword differs 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, although 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;
continue The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears.
decimal The decimal keyword indicates a 128-bit data type. Compared to floating-point types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations.Approximate Range: (-7.9 x 1028 to 7.9 x 1028) / (100 to 28)Precision: 28-29 significant digits.
   
default The default keyword.The default keyword can be used in the switch statement or in generic code:

  • The switch statement: Specifies the default label.
  • Generic code: Specifies the default value of the type parameter. This will be null for reference types and zero for value types.
delegate The declaration of a delegate type is similar to a method signature. It has a return value and any number of parameters of any type.A delegate is a reference type that can be used to encapsulate a named or an anonymous method. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure. For applications of delegates, see Delegates and Generic Delegates.Delegates are the basis for Events.A delegate can be instantiated by associating it either with a named or anonymous method. For more information, see Named Methods and Anonymous Methods.The delegate must be instantiated with a method or lambda expression that has a compatible return type and input parameters. For more information on the degree of variance that is allowed in the method signature, see Variance in Delegates (C# and Visual Basic). For use with anonymous methods, the delegate and the code to be associated with it are declared together.
do The do statement executes a statement or a block of statements enclosed in {} repeatedly until a specified expression evaluates to false.
double The double keyword signifies a simple type that stores 64-bit floating-point valuesApproximate Range: ±5.0 × 10−324 to ±1.7 × 10308Precision: 15-16 digits.
else The if statement selects a statement for execution based on the value of a Boolean expression. In case result is false, else block will be executed.
enum The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.Usually it is best to define an enum directly within a namespace so that all classes in the namespace can access it with equal convenience. However, an enum can also be nested within a class or struct.By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
event The event keyword is used to declare an event in a publisher class.public class SampleEventArgs{public SampleEventArgs(string s) { Text = s; }public String Text {get; private set;} // readonly}

public class Publisher

{

// Declare the delegate (if using non-generic pattern).

public delegate void SampleEventHandler(object sender, SampleEventArgs e);

// Declare the event.

public event SampleEventHandler SampleEvent;

// Wrap the event in a protected virtual method

// to enable derived classes to raise the event.

protected virtual void RaiseSampleEvent()

{

// Raise the event by using the () operator.

if (SampleEvent != null)

SampleEvent(this, new SampleEventArgs(“Hello”));

}

}

Events are a special kind of multicast delegate that can only be invoked from within the class or struct where they are declared (the publisher class). If other classes or structs subscribe to the event, their event handler methods will be called when the publisher class raises the event.

Events can be marked as public, private, protected, internal, or protectedinternal. These access modifiers define how users of the class can access the event.

explicit The explicit keyword declares a user-defined type conversion operator that must be invoked with a cast. For example, this operator converts from a class called Fahrenheit to a class called Celsius:// Must be defined inside a class called Farenheit:public static explicit operator Celsius(Fahrenheit f){return new Celsius((5.0f / 9.0f) * (f.degrees – 32));}

This conversion operator can be invoked like this:

Fahrenheit f = new Fahrenheit(100.0f);

Console.Write(“{0} fahrenheit”, f.Degrees);

Celsius c = (Celsius)f;

The conversion operator converts from a source type to a target type. The source type provides the conversion operator. Unlike implicit conversion, explicit conversion operators must be invoked by means of a cast. If a conversion operation can cause exceptions or lose information, you should mark it explicit. This prevents the compiler from silently invoking the conversion operation with possibly unforeseen consequences.

extern The extern modifier is used to declare a method that is implemented externally. A common use of the extern modifier is with the DllImport attribute when you are using Interop services to call into unmanaged code. In this case, the method must also be declared as static, as shown in the following example:[DllImport(“avifil32.dll”)]private static extern void AVIFileInit();The extern keyword can also define an external assembly alias, which makes it possible to reference different versions of the same component from within a single assembly. For more information, see extern alias (C# Reference).It is an error to use the abstract (C# Reference) and extern modifiers together to modify the same member. Using the extern modifier means that the method is implemented outside the C# code, whereas using the abstract modifier means that the method implementation is not provided in the class.
false Used as an overloaded operator or as a literal:

  • false Operator : Returns the bool value true to indicate that an operand is false and returns false otherwise. Prior to C# 2.0, the true and false operators were used to create user-defined nullable value types that were compatible with types such as SqlBool. However, the language now provides built-in support for nullable value types, and whenever possible you should use those instead of overloading the true and false operators. For more information, see Nullable Types (C# Programming Guide).
  • false Literal : Represents the boolean value false.
finally The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.Whereas catch is used to handle exceptions that occur in a statement block, finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited.
fixed The fixed statement prevents the garbage collector from relocating a movable variable. The fixed statement is only permitted in an unsafe context. Fixed can also be used to create fixed size buffers.The fixed statement sets a pointer to a managed variable and “pins” that variable during the execution of the statement. Without fixed, pointers to movable managed variables would be of little use since garbage collection could relocate the variables unpredictably. The C# compiler only lets you assign a pointer to a managed variable in a fixed statement.unsafe static void TestMethod(){// assume class Point { public int x, y; }// pt is a managed variable, subject to garbage collection.

Point pt = new Point();

// Using fixed allows the address of pt members to be

// taken, and “pins” pt so it isn’t relocated.

fixed (int* p = &pt.x)

{

*p = 1;

}

}

float The float keyword signifies a simple type that stores 32-bit floating-point values.float x = 3.5F;If you do not use the suffix in the previous declaration, you will get a compilation error because you are trying to store a double value into a float variable.
for The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The for loop is useful for iterating over arrays and for sequential processing.
foreach The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface. The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.The embedded statements continue to execute for each element in the array or collection. After the iteration has been completed for all the elements in the collection, control is transferred to the next statement following the foreach block.At any point within the foreach block, you can break out of the loop by using the break keyword, or step to the next iteration in the loop by using the continue keyword.A foreach loop can also be exited by the goto, return, or throwstatements.
goto The goto statement transfers the program control directly to a labeled statement.A common use of goto is to transfer control to a specific switch-case label or the default label in a switch statement.The goto statement is also useful to get out of deeply nested loops.
if The if statement selects a statement for execution based on the value of a Boolean expression.
implicit The implicit keyword is used to declare an implicit user-defined type conversion operator. Use it to enable implicit conversions between a user-defined type and another type, if the conversion is guaranteed not to cause a loss of data.class Digit{public Digit(double d) { val = d; }public double val;// …other members

// User-defined conversion from Digit to double

public static implicit operator double(Digit d)

{

return d.val;

}

// User-defined conversion from double to Digit

public static implicit operator Digit(double d)

{

return new Digit(d);

}

}

Digit dig = new Digit(7);

//This call invokes the implicit “double” operator

double num = dig;

//This call invokes the implicit “Digit” operator

Digit dig2 = 12;

in The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable<T> interface. The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects. If you need to add or remove items from the source collection, use a for loop.The embedded statements continue to execute for each element in the array or collection. After the iteration has been completed for all the elements in the collection, control is transferred to the next statement following the foreach block.At any point within the foreach block, you can break out of the loop by using the break keyword, or step to the next iteration in the loop by using the continue keyword.A foreach loop can also be exited by the goto, return, or throwstatements.
in (generic modifier) For generic type parameters, the in keyword specifies that the type parameter is contravariant. You can use the in keyword in generic interfaces and delegates.Contravariance enables you to use a less derived type than that specified by the generic parameter. This allows for implicit conversion of classes that implement variant interfaces and implicit conversion of delegate types. Covariance and contravariance in generic type parameters are supported for reference types, but they are not supported for value types.A type can be declared contravariant in a generic interface or delegate if it is used only as a type of method arguments and not used as a method return type. Ref and out parameters cannot be variant.An interface that has a contravariant type parameter allows its methods to accept arguments of less derived types than those specified by the interface type parameter. For example, because in .NET Framework 4, in the IComparer<T> interface, type T is contravariant, you can assign an object of the IComparer(Of Person) type to an object of the IComparer(Of Employee) type without using any special conversion methods if Person inherits Employee.A contravariant delegate can be assigned another delegate of the same type, but with a less derived generic type parameter.
int The int keyword denotes an integral type that stores values according to the size (Signed 32-bit integer) and range (-2,147,483,648 to 2,147,483,647)
interface An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.An interface can be a member of a namespace or a class and can contain signatures of the following members:

An interface can inherit from one or more base interfaces.

When a base type list contains a base class and interfaces, the base class must come first in the list.

A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.

For more details and code examples on explicit interface implementation, see Explicit Interface Implementation (C# Programming Guide). Or read below

Explicit Interface :

If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.

interface IControl

{

void Paint();

}

interface ISurface

{

void Paint();

}

class SampleClass : IControl, ISurface

{

// Both ISurface.Paint and IControl.Paint call this method.

public void Paint()

{

}

}

 

If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces. It is possible to implement an interface member explicitly—creating a class member that is only called through the interface, and is specific to that interface. This is accomplished by naming the class member with the name of the interface and a period.

public class SampleClass : IControl, ISurface

{

void IControl.Paint()

{

System.Console.WriteLine(“IControl.Paint”);

}

void ISurface.Paint()

{

System.Console.WriteLine(“ISurface.Paint”);

}

}

Explicit implementation is also used to resolve cases where two interfaces each declare different members of the same name such as a property and a method:

internal The internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly.A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code. For example, a framework for building graphical user interfaces could provide Control and Form classes that cooperate by using members with internal access. Since these members are internal, they are not exposed to code that is using the framework.
is Checks if an object is compatible with a given type.An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.The is keyword causes a compile-time warning if the expression is known to always be true or to always be false, but typically evaluates type compatibility at run time.The is operator cannot be overloaded.Note that the is operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered.Anonymous methods are not allowed on the left side of the is operator. This exception includes lambda expressions.
lock The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. This statement takes the following form:Object thisLock = new Object();lock (thisLock){// Critical code section.}

The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

The lock keyword calls Enter at the start of the block and Exit at the end of the block.

In general, avoid locking on a public type, or instances beyond your code’s control. The common constructs lock (this), lock (typeof (MyType)), and lock (“myLock”) violate this guideline:

  • lock (this) is a problem if the instance can be accessed publicly.
  • lock (typeof (MyType)) is a problem if MyType is publicly accessible.
  • lock(“myLock”) is a problem because any other code in the process using the same string, will share the same lock.

Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.

long The long keyword denotes an integral type that stores values according to the size (Signed 64-bit integer) and range (–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
namespace The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally unique types.Within a namespace, you can declare one or more of the following types:

Whether or not you explicitly declare a namespace in a C# source file, the compiler adds a default namespace. This unnamed namespace, sometimes referred to as the global namespace, is present in every file. Any identifier in the global namespace is available for use in a named namespace.

Namespaces implicitly have public access and this is not modifiable.

new In C#, the new keyword can be used as an operator, a modifier, or a constraint.new OperatorUsed to create objects and invoke constructors.new ModifierUsed to hide an inherited member from a base class member.When used as a modifier, the new keyword explicitly hides a member inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base-class version. Although you can hide members without the use of the new modifier, the result is a warning. If you use new to explicitly hide a member, it suppresses this warning and documents the fact that the derived version is intended as a replacement.

public class BaseC

{

public int x;

public void Invoke() { }

}

public class DerivedC : BaseC

{

new public void Invoke() { }

}

new Constraint

Used to restrict types that might be used as arguments for a type parameter in a generic declaration.

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.

Apply the new constraint to a type parameter when your generic class creates new instances of the type, as shown in the following example:

class ItemFactory<T> where T : new()

{

public T GetNewItem()

{

return new T();

}

}

null The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables. Ordinary value types cannot be null. However, C# 2.0 introduced nullable value types. See Nullable Types (C# Programming Guide).
object The object type is an alias for Object in the .NET Framework. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. You can assign values of any type to variables of type object. When a variable of a value type is converted to object, it is said to be boxed. When a variable of type object is converted to a value type, it is said to be unboxed.
operator Use the operator keyword to overload a built-in operator or to provide a user-defined conversion in a class or struct declaration.
out The out contextual keyword is used in two contexts:

  • parameter modifier in parameter lists : The out keyword causes arguments to be passed by reference. This is like the ref keyword, except that ref requires that the variable be initialized before it is passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.

generic type parameters in generic interfaces and delegates : For generic type parameters, the out keyword specifies that the type parameter is covariant. You can use the out keyword in generic interfaces and delegates.

Covariance enables you to use a more derived type than that specified by the generic parameter. This allows for implicit conversion of classes that implement variant interfaces and implicit conversion of delegate types. Covariance and contravariance are supported for reference types, but they are not supported for value types.

An interface that has a covariant type parameter enables its methods to return more derived types than those specified by the type parameter. For example, because in .NET Framework 4, in IEnumerable<T>, type T is covariant, you can assign an object of the IEnumerabe(Of String) type to an object of the IEnumerable(Of Object) type without using any special conversion methods.

A covariant delegate can be assigned another delegate of the same type, but with a more derived generic type parameter.

For more information, see Covariance and Contravariance (C# and Visual Basic).

// Covariant interface.

interface ICovariant<out R> { }

// Extending covariant interface.

interface IExtCovariant<out R> : ICovariant<R> { }

// Implementing covariant interface.

class Sample<R> : ICovariant<R> { }

ICovariant<Object> iobj = new Sample<Object>();

ICovariant<String> istr = new Sample<String>();

// You can assign istr to iobj because

// the ICovariant interface is covariant.

iobj = istr;

out (generic modifier) See above
override The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.An override method provides a new implementation of a member that is inherited from a base class. The method that is overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method. For information about inheritance, see Inheritance (C# Programming Guide).You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.You cannot use the new, static, or virtual modifiers to modify an override method.An overriding property declaration must specify exactly the same access modifier, type, and name as the inherited property, and the overridden property must be virtual, abstract, or override.

For more information about how to use the override keyword, see Versioning with the Override and New Keywords (C# Programming Guide) and Knowing when to use Override and New Keywords.

params The params keyword lets you specify a method parameter that takes a variable number of arguments.You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments.No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.
private The private keyword is a member access modifier. Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared.Nested types in the same body can also access those private members.It is a compile-time error to reference a private member outside the class or the struct in which it is declared.
protected The protected keyword is a member access modifier. A protected member is accessible within its class and by derived class instances. For a comparison of protected with the other access modifiers, see Accessibility Levels.
public The public keyword is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members.
readonly The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
ref The ref keyword causes arguments to be passed by reference. The effect is that any changes to the parameter in the method will be reflected in that variable when control passes back to the calling method.Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not related; a method parameter can be modified by ref regardless of whether it is a value type or a reference type. Therefore, there is no boxing of a value type when it is passed by reference.To use a ref parameter, both the method definition and the calling method must explicitly use the ref keyword.
return The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return an optional value. If the method is a void type, the return statement can be omitted.If the return statement is inside a try block, the finally block, if one exists, will be executed before control returns to the calling method.
sbyte The sbyte keyword indicates an integral type that stores values according to the size (Signed 8-bit integer) and range (-128 to 127)
sealed When applied to a class, the sealed modifier prevents other classes from inheriting from it. In the following example, class B inherits from class A, but no class can inherit from class B.You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.
short The short keyword denotes an integral data type that stores values according to the size(Signed 16-bit integer) and range (-32,768 to 32,767)
sizeof Used to obtain the size in bytes for an unmanaged type. Unmanaged types include the built-in types that are listed in the table that follows, and also the following:

  • Enum types
  • Pointer types
  • User-defined structs that do not contain any fields or properties that are reference types
stackalloc The stackalloc keyword is used in an unsafe code context to allocate a block of memory on the stack.int* block = stackalloc int[100];
static Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes. For more information, see Static Classes and Static Class Members (C# Programming Guide).A constant or type declaration is implicitly a static member.A static member cannot be referenced through an instance. Instead, it is referenced through the type name.While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field.It is not possible to use this to reference static methods or property accessors.If the static keyword is applied to a class, all the members of the class must be static.

Classes and static classes may have static constructors. Static constructors are called at some point between when the program starts and the class is instantiated.

string The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework.Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive.Strings are immutable–the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this.
struct A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory.Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types, although if several such members are required, you should consider making your type a class instead.Structs can implement an interface but they cannot inherit from another struct. For that reason, struct members cannot be declared as protected.
switch The switch statement is a control statement that selects a switch section to execute from a list of candidates.Each switch section contains one or more case labels and a list of one or more statements. The following example shows a simple switch statement that has three switch sections. Each switch section has one case label, such as case 1, and a list of two statements.
this The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.see Extension Methods (C# Programming Guide).: Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.namespace ExtensionMethods{public static class MyExtensions{

public static int WordCount(this String str)

{

return str.Split(new char[] { ‘ ‘, ‘.’, ‘?’ }, StringSplitOptions.RemoveEmptyEntries).Length;

}

}

}

The following example shows an extension method defined for the System.String class.

throw The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution.Usually the throw statement is used with try-catch or try-finally statements.
true Used as an overloaded operator or as a literal:true Operator : Returns the bool value true to indicate that an operand is true and returns false otherwise. The language now provides built-in support for nullable value types, and whenever possible you should use those instead of overloading the true and false operators. For more information, see Nullable Types (C# Programming Guide).true Literal : Represents the boolean value true.
try The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions. When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.
typeof Used to obtain the System.Type object for a type. A typeof expression takes the following form:System.Type type = typeof(int);
uint The uint keyword signifies an integral type that stores values according to the size (Unsigned 32-bit integer) and range (0 to 4,294,967,295)
ulong The ulong keyword signifies an integral type that stores values according to the size (Unsigned 64-bit integer) and range (0 to 18,446,744,073,709,551,615)
unchecked The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.In an unchecked context, if an expression produces a value that is outside the range of the destination type, the overflow is not flagged. For example, because the calculation in the following example is performed in an unchecked block or expression, the fact that the result is too large for an integer is ignored, and int1 is assigned the value -2,147,483,639.unchecked{int1 = 2147483647 + 10;}

int1 = unchecked(ConstantMax + 10);

unsafe The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers. For more information, see Unsafe Code and Pointers (C# Programming Guide).You can use the unsafe modifier in the declaration of a type or a member. The entire textual extent of the type or member is therefore considered an unsafe context. For example, the following is a method declared with the unsafe modifier:To compile unsafe code, you must specify the /unsafe compiler option. Unsafe code is not verifiable by the common language runtime.
ushort The ushort keyword indicates an integral data type that stores values according to the size(Unsigned 16-bit integer) and range (0 to 65,535)
using The using keyword has two major uses:

  • As a directive, when it is used to create an alias for a namespace or to import types defined in other namespaces. See using Directive.

As a statement, when it defines a scope at the end of which an object will be disposed. See using Statement : Provides a convenient syntax that ensures the correct use of IDisposable objects. File and Font are examples of managed types that access unmanaged resources (in this case file handles and device contexts). There are many other kinds of unmanaged resources and class library types that encapsulate them. All such types must implement the IDisposable interface.

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

virtual The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it:public virtual double Area(){return x * y;}The implementation of a virtual member can be changed by an overriding member in a derived class. For more information about how to use the virtual keyword, see Versioning with the Override and New Keywords (C# Programming Guide) and Knowing When to Use Override and New Keywords (C# Programming Guide).

When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

By default, methods are non-virtual. You cannot override a non-virtual method.

You cannot use the virtual modifier with the static, abstract, private, or override modifiers.

Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax.

  • It is an error to use the virtual modifier on a static property.
  • A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
void When used as the return type for a method, void specifies that the method does not return a value.void is not allowed in the parameter list of a method.void is also used in an unsafe context to declare a pointer to an unknown type. For more information, see Pointer types (C# Programming Guide).void is an alias for the .NET Framework System.Void type.
volatile The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.The volatile keyword can be applied to fields of these types:

  • Reference types.
  • Pointer types (in an unsafe context). Note that although the pointer itself can be volatile, the object that it points to cannot. In other words, you cannot declare a “pointer to volatile.”
  • Types such as sbyte, byte, short, ushort, int, uint, char, float, and bool.
  • An enum type with one of the following base types: byte, sbyte, short, ushort, int, or uint.
  • Generic type parameters known to be reference types.
  • IntPtr and UIntPtr.

The volatile keyword can only be applied to fields of a class or struct. Local variables cannot be declared volatile.

The following example demonstrates how an auxiliary or worker thread can be created and used to perform processing in parallel with that of the primary thread. For background information about multithreading, see Managed Threading and Threading (C# and Visual Basic).

using System;

using System.Threading;

public class Worker

{

// This method is called when the thread is started.

public void DoWork()

{

while (!_shouldStop)

{

Console.WriteLine(“Worker thread: working…”);

}

Console.WriteLine(“Worker thread: terminating gracefully.”);

}

public void RequestStop()

{

_shouldStop = true;

}

// Keyword volatile is used as a hint to the compiler that this data

// member is accessed by multiple threads.

private volatile bool _shouldStop;

}

public class WorkerThreadExample

{

static void Main()

{

// Create the worker thread object. This does not start the thread.

Worker workerObject = new Worker();

Thread workerThread = new Thread(workerObject.DoWork);

// Start the worker thread.

workerThread.Start();

Console.WriteLine(“Main thread: starting worker thread…”);

// Loop until the worker thread activates.

while (!workerThread.IsAlive) ;

// Put the main thread to sleep for 1 millisecond to

// allow the worker thread to do some work.

Thread.Sleep(1);

// Request that the worker thread stop itself.

workerObject.RequestStop();

// Use the Thread.Join method to block the current thread

// until the object’s thread terminates.

workerThread.Join();

Console.WriteLine(“Main thread: worker thread has terminated.”);

}

// Sample output:

// Main thread: starting worker thread…

// Worker thread: working…

// Worker thread: working…

// Worker thread: working…

// Worker thread: working…

// Worker thread: working…

// Worker thread: working…

// Worker thread: terminating gracefully.

// Main thread: worker thread has terminated.

}

while The while statement executes a statement or a block of statements until a specified expression evaluates to false.

Contextual Keywords


A contextual keyword is used to provide a specific meaning in the code, but it is not a reserved word in C#. Some contextual keywords, such as partial and where, have special meanings in two or more contexts.

Keywords Description
add The add contextual keyword is used to define a custom event accessor that is invoked when client code subscribes to your event. If you supply a custom add accessor, you must also supply a remove accessor.class Events : IDrawingObject{event EventHandler PreDrawEvent;event EventHandler IDrawingObject.OnDraw{

add

{

lock (PreDrawEvent)

{

PreDrawEvent += value;

}

}

remove

{

lock (PreDrawEvent)

{

PreDrawEvent -= value;

}

}

}

}

You do not typically need to provide your own custom event accessors. The accessors that are automatically generated by the compiler when you declare an event are sufficient for most scenarios.

alias You might have to reference two versions of assemblies that have the same fully-qualified type names. For example, you might have to use two or more versions of an assembly in the same application. By using an external assembly alias, the namespaces from each assembly can be wrapped inside root-level namespaces named by the alias, which enables them to be used in the same file.To reference two assemblies with the same fully-qualified type names, an alias must be specified at a command prompt, as follows:/r:GridV1=grid.dll/r:GridV2=grid20.dllThis creates the external aliases GridV1 and GridV2. To use these aliases from within a program, reference them by using the extern keyword. For example:extern alias GridV1;

extern alias GridV2;

Each extern alias declaration introduces an additional root-level namespace that parallels (but does not lie within) the global namespace. Thus types from each assembly can be referred to without ambiguity by using their fully qualified name, rooted in the appropriate namespace-alias.

ascending The ascending contextual keyword is used in the orderby clause in query expressions to specify that the sort order is from smallest to largest. Because ascending is the default sort order, you do not have to specify it.IEnumerable<string> sortAscendingQuery =from vegetable in vegetablesorderby vegetable ascendingselect vegetable;See : LINQ Query Expressions (C# Programming Guide)
descending The descending contextual keyword is used in the orderby clause in query expressions to specify that the sort order is from largest to smallest.
dynamic The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time. The type simplifies access to COM APIs such as the Office Automation APIs, and also to dynamic APIs such as IronPython libraries, and to the HTML Document Object Model (DOM).Type dynamic behaves like type object in most circumstances. However, operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time. As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.class Program{static void Main(string[] args){

dynamic dyn = 1;

object obj = 1;

// Rest the mouse pointer over dyn and obj to see their

// types at compile time.

System.Console.WriteLine(dyn.GetType());

System.Console.WriteLine(obj.GetType());

}

}

The following example contrasts a variable of type dynamic to a variable of type object. To verify the type of each variable at compile time, place the mouse pointer over dyn or obj in the WriteLine statements. IntelliSense shows dynamic for dyn and object for obj.

from A query expression must begin with a from clause. Additionally, a query expression can contain sub-queries, which also begin with a from clause. The from clause specifies the following:

  • The data source on which the query or sub-query will be run.
  • A local range variable that represents each element in the source sequence.

Both the range variable and the data source are strongly typed. The data source referenced in the from clause must have a type of IEnumerable, IEnumerable<T>, or a derived type such as IQueryable<T>.

get The get keyword defines an accessor method in a property or indexer that retrieves the value of the property or the indexer element. For more information, see Properties (C# Programming Guide), Auto-Implemented Properties (C# Programming Guide) and Indexers (C# Programming Guide).
global The global contextual keyword, when it comes before the :: operator, refers to the global namespace, which is the default namespace for any C# program and is otherwise unnamed. For more information, see How to: Use the Namespace Alias Qualifier (C# Programming Guide).class TestClass : global::TestApp { }
group The group clause returns a sequence of IGrouping<TKey, TElement> objects that contain zero or more items that match the key value for the group. For example, you can group a sequence of strings according to the first letter in each string. In this case, the first letter is the key and has a type char, and is stored in the Key property of each IGrouping<TKey, TElement> object. The compiler infers the type of the key.You can end a query expression with a group clause, as shown in the following example:// Query variable is an IEnumerable<IGrouping<char, Student>>var studentQuery1 =from student in studentsgroup student by student.Last[0];

If you want to perform additional query operations on each group, you can specify a temporary identifier by using the into contextual keyword. When you use into, you must continue with the query, and eventually end it with either a select statement or another group clause, as shown in the following excerpt:

// Group students by the first letter of their last name

// Query variable is an IEnumerable<IGrouping<char, Student>>

var studentQuery2 =

from student in students

group student by student.Last[0] into g

orderby g.Key

select g;

into The into contextual keyword can be used to create a temporary identifier to store the results of a group, join or select clause into a new identifier. This identifier can itself be a generator for additional query commands. When used in a group or select clause, the use of the new identifier is sometimes referred to as a continuation.
join The join clause is useful for associating elements from different source sequences that have no direct relationship in the object model. The only requirement is that the elements in each source share some value that can be compared for equality. For example, a food distributor might have a list of suppliers of a certain product, and a list of buyers. A join clause can be used, for example, to create a list of the suppliers and buyers of that product who are all in the same specified region.A join clause takes two source sequences as input. The elements in each sequence must either be or contain a property that can be compared to a corresponding property in the other sequence. The join clause compares the specified keys for equality by using the special equals keyword. All joins performed by the join clause are equijoins. The shape of the output of a join clause depends on the specific type of join you are performing. The following are three most common join types:

  • Inner join
  • Group join : A group join produces a hierarchical result sequence, which associates elements in the left source sequence with one or more matching elements in the right side source sequence. A group join has no equivalent in relational terms; it is essentially a sequence of object arrays.
  • Left outer join

var innerJoinQuery =

from category in categories

join prod in products on category.ID equals prod.CategoryID

select new { ProductName = prod.Name, Category = category.Name }; //produces flat sequence

let In a query expression, it is sometimes useful to store the result of a sub-expression in order to use it in subsequent clauses. You can do this with the let keyword, which creates a new range variable and initializes it with the result of the expression you supply. Once initialized with a value, the range variable cannot be used to store another value. However, if the range variable holds a queryable type, it can be queried.string[] strings ={“A penny saved is a penny earned.”,”The early bird catches the worm.”,”The pen is mightier than the sword.”

};

// Split the sentence into an array of words

// and select those whose first letter is a vowel.

var earlyBirdQuery =

from sentence in strings

let words = sentence.Split(‘ ‘)

from word in words

let w = word.ToLower()

where w[0] == ‘a’ || w[0] == ‘e’

|| w[0] == ‘i’ || w[0] == ‘o’

|| w[0] == ‘u’

select word;

orderby In a query expression, the orderby clause causes the returned sequence or subsequence (group) to be sorted in either ascending or descending order. Multiple keys can be specified in order to perform one or more secondary sort operations. The sorting is performed by the default comparer for the type of the element. The default sort order is ascending. You can also specify a custom comparer. However, it is only available by using method-based syntax. For more information, see Sorting Data.
partial (type) Partial type definitions allow for the definition of a class, struct, or interface to be split into multiple files. Splitting a class, struct or interface type over several files can be useful when you are working with large projects, or with automatically generated code such as that provided by the Windows Forms Designer. A partial type may contain a partial method. For more information, see Partial Classes and Methods (C# Programming Guide).
partial (method) A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not. If the developer does not supply an implementation, the compiler removes the signature at compile time. The following conditions apply to partial methods:

  • Signatures in both parts of the partial type must match.
  • The method must return void.
  • No access modifiers or attributes are allowed. Partial methods are implicitly private.
remove The remove contextual keyword is used to define a custom event accessor that is invoked when client code unsubscribes from your event. If you supply a custom remove accessor, you must also supply an add accessor.
select In a query expression, the select clause specifies the type of values that will be produced when the query is executed. The result is based on the evaluation of all the previous clauses and on any expressions in the select clause itself. A query expression must terminate with either a select clause or a group clause.//Create the data sourceList<int> Scores = new List<int>() { 97, 92, 81, 60 };// Create the query.IEnumerable<int> queryHighScores =from score in Scores

where score > 80

select score;

set The set keyword defines an accessor method in a property or indexer that assigns the value of the property or the indexer element. For more information, see Properties (C# Programming Guide), Auto-Implemented Properties (C# Programming Guide), and Indexers (C# Programming Guide).
value The contextual keyword value is used in the set accessor in ordinary property declarations. It is similar to an input parameter on a method. The word value references the value that client code is attempting to assign to the property. In the following example, MyDerivedClass has a property called Name that uses the value parameter to assign a new string to the backing field name. From the point of view of client code, the operation is written as a simple assignment.class MyBaseClass{// virtual auto-implemented property. Overrides can only// provide specialized behavior if they implement get and set accessors.public virtual string Name { get; set; }

// ordinary virtual property with backing field

private int num;

public virtual int Number

{

get { return num; }

set { num = value; }

}

}

class MyDerivedClass : MyBaseClass

{

private string name;

// Override auto-implemented property with ordinary property

// to provide specialized accessor behavior.

public override string Name

{

get

{

return name;

}

set

{

if (value != String.Empty)

{

name = value;

}

else

{

name = “Unknown”;

}

}

}

}

var Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:var i = 10; // implicitly typedint i = 10; //explicitly typed
where (generic type constraint) In a generic type definition, the where clause is used to specify constraints on the types that can be used as arguments for a type parameter defined in a generic declaration. For example, you can declare a generic class, MyGenericClass, such that the type parameter T implements the IComparable<T> interface:For more information on the where clause in a query expression, see where clause (C# Reference).
where (query clause) The where clause is used in a query expression to specify which elements from the data source will be returned in the query expression. It applies a Boolean condition (predicate) to each source element (referenced by the range variable) and returns those for which the specified condition is true. A single query expression may contain multiple where clauses and a single clause may contain multiple predicate subexpressions.
yield The yield keyword signals to the compiler that the method in which it appears is an iterator block. The compiler generates a class to implement the behavior that is expressed in the iterator block. In the iterator block, the yield keyword is used together with the return keyword to provide a value to the enumerator object. This is the value that is returned, for example, in each loop of a foreach statement. The yield keyword is also used with break to signal the end of iteration. For more information about iterators, see Iterators (C# Programming Guide). The following example shows the two forms of the yield statement.yield return <expression>;yield break;In a yield return statement, expression is evaluated and returned as a value to the enumerator object; expression has to be implicitly convertible to the yield type of the iterator.In a yield break statement, control is unconditionally returned to the caller of the iterator, which is either the IEnumerator.MoveNext method (or its generic System.Collections.Generic.IEnumerable<T> counterpart) or the Dispose method of the enumerator object.The yield statement can only appear inside an iterator block, which can be implemented as the body of a method, operator, or accessor. The body of such methods, operators, or accessors is controlled by the following restrictions:

  • Unsafe blocks are not allowed.
  • Parameters to the method, operator, or accessor cannot be ref or out.
  • A yield return statement cannot be located anywhere inside a try-catch block. It can be located in a try block if the try block is followed by a finally block.
  • A yield break statement may be located in a try block or a catch block but not a finally block.

A yield statement cannot appear in an anonymous method. For more information, see Anonymous Methods (C# Programming Guide).

When used with expression, a yield return statement cannot appear in a catch block or in a try block that has one or more catch clauses. For more information, see Exception Handling Statements (C# Reference).

public class List

{

//using System.Collections;

public static IEnumerable Power(int number, int exponent)

{

int counter = 0;

int result = 1;

while (counter++ < exponent)

{

result = result * number;

yield return result;

}

}

static void Main()

{

// Display powers of 2 up to the exponent 8:

foreach (int i in Power(2, 8))

{

Console.Write(“{0} “, i);

}

}

}

/*

Output:

2 4 8 16 32 64 128 256

*/

You may be interested in The C# Language on msdn which will cover C# Operators , C# Preprocessor Directives, C# Language Features and C# Language Tutorials.

The above article contents are from MSDN links mentioned above and whole credit goes to msdn team for proving such an extensive information. The purpose of this article is to quickly review the c# concepts and fill in the gaps in articles that appears under .Net Concepts on this blog.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s