Skip to main content

Posts

Showing posts with the label C# Fundamentals

Implicitly Typed Local Variables in C#

Local variables can be given an inferred "type" of  var  instead of an explicit type. The  var  keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.  The following examples show various ways in which local variables can be declared with  var : // i is compiled as an int var i = 5; // s is compiled as a string var s = "Hello" ; // a is compiled as int[] var a = new [] { 0, 1, 2 }; // expr is compiled as IEnumerable<Customer> // or perhaps IQueryable<Customer> var expr = from c in customers where c.City == "London" select c; // anon is compiled as an anonymous type var anon = new { Name = "Terry" , Age = 34 }; // list is compiled as List<int> var ...

Structs in C#

Like classes, structs are data structures that can contain data members and function members, but unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly stores the data of the struct, whereas a variable of a class type stores a reference to a dynamically allocated object. Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object . Structs are particularly useful for small data structures that have value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs. The use of structs rather than classes for small data structures can make a large difference in the number of memory allocations an application performs. For example, the following program creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated—one for the array and one each for...

Events in C#

An event is a member that enables a class or object to provide notifications. An event is declared like a field except that the declaration includes an event keyword and the type must be a delegate type. Within a class that declares an event member, the event behaves just like a field of a delegate type (provided the event is not abstract and does not declare accessors). The field stores a reference to a delegate that represents the event handlers that have been added to the event. If no event handles are present, the field is null . The List<T> class declares a single event member called Changed , which indicates that a new item has been added to the list. The Changed event is raised by the OnChanged virtual method, which first checks whether the event is null (meaning that no handlers are present). The notion of raising an event is precisely equivalent to invoking the delegate represented by the event—thus, there are no special language constructs for raising even...

Static Constructors

A static constructor is used to initialize any  static  data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced. Code :-  class SimpleClass { // Static variable that must be initialized at run time.  static   readonly   long baseline; // Static constructor is called at most one time, before any  // instance constructor is invoked or member is accessed.  static SimpleClass() { baseline = DateTime.Now.Ticks; } } Static constructors have the following properties: 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...

Properties in C#

Properties are a natural extension of fields. Both are named members with associated types, and the syntax for accessing fields and properties is the same. However, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the statements to be executed when their values are read or written. A property is declared like a field, except that the declaration ends with a get accessor and/or a set accessor written between the delimiters { and } instead of ending in a semicolon. A property that has both a get accessor and a set accessor is a read-write property , a property that has only a get accessor is a read-only property , and a property that has only a set accessor is a write-only property . A get accessor corresponds to a parameterless method with a return value of the property type. Except as the target of an assignment, when a property is referenced in an expression, the get accessor of the property is invoked to ...

Constructors in C#

C# supports both instance and static constructors. An instance constructor is a member that implements the actions required to initialize an instance of a class. A static constructor is a member that implements the actions required to initialize a class itself when it is first loaded. A constructor is declared like a method with no return type and the same name as the containing class. If a constructor declaration includes a static modifier, it declares a static constructor. Otherwise, it declares an instance constructor. Instance constructors can be overloaded. For example, the List<T> class declares two instance constructors, one with no parameters and one that takes an int parameter. Instance constructors are invoked using the new operator. The following statements allocate two List<string> instances using each of the constructors of the List class. List<string> list1 = new List<string>(); List<string> list2 = new List<strin...

Method overloading (C# Specification Part 9)

Method overloading permits multiple methods in the same class to have the same name as long as they have unique signatures. When compiling an invocation of an overloaded method, the compiler uses overload resolution to determine the specific method to invoke. Overload resolution finds the one method that best matches the arguments or reports an error if no single best match can be found. The following example shows overload resolution in effect. The comment for each invocation in the Main method shows which method is actually invoked. class Test {       static void F() {             Console.WriteLine("F()");       }       static void F(object x) {             Console.WriteLine("F(object)");       }       static void F(int x) {  ...

Virtual, Override, and Abstract methods ( C# Specification Part 8)

When an instance method declaration includes a virtual modifier, the method is said to be a virtual method . When no virtual modifier is present, the method is said to be a non-virtual method . When a virtual method is invoked, the run-time type of the instance for which that invocation takes place determines the actual method implementation to invoke. In a nonvirtual method invocation, the compile-time type of the instance is the determining factor. A virtual method can be overridden in a derived class. When an instance method declaration includes an override modifier, the method overrides an inherited virtual method with the same signature. Whereas a virtual method declaration introduces a new method, an override method declaration specializes an existing inherited virtual method by providing a new implementation of that method. An abstract method is a virtual method with no implementation. An abstract method is declared with the abstract modifier and is permitt...

Methods (C# Specification Part 7)

A method’s body specifies the statements to execute when the method is invoked. A method body can declare variables that are specific to the invocation of the method. Such variables are called local variables . A local variable declaration specifies a type name, a variable name, and possibly an initial value. The following example declares a local variable i with an initial value of zero and a local variable j with no initial value. using System; class Squares {       static void Main () {             int i = 0;             int j;             while (i < 10) {                   j = i * i;                   Console....

Classes and objects (C# Specification Part 6)

Classes are the most fundamental of C#’s types. A class is a data structure that combines state (fields) and actions (methods and other function members) in a single unit. A class provides a definition for dynamically created instances of the class, also known as objects . Classes support inheritance and polymorphism , mechanisms whereby derived classes can extend and specialize base classes . New classes are created using class declarations. A class declaration starts with a header that specifies the attributes and modifiers of the class, the name of the class, the base class (if given), and the interfaces implemented by the class. The header is followed by the class body, which consists of a list of member declarations written between the delimiters { and } . The following is a declaration of a simple class named Point : public class Point {       public int x, y;       public Point(int x, int y) {   ...