October 2007


There are different modifiers which decide the visibility of the types or members.

They are:

Modifier

Applies To Description
public Any types or members The item is visible to any other code.
protected Any member of a type, also any nested type The item is visible only to any derived type.
internal Any member of a type, also any nested type The item is visible only within its containing assembly.
private Any types or members The item is visible only inside the type to which it belongs.
protected internal Any member of a type, also any nested type The item is visible to any code within its containing assembly and also to any code inside a derived type.

Some other modifiers are:

Modifier

Applies To Description
public Any types or members The item is visible to any other code.
protected Any member of a type, also any nested type The item is visible only to any derived type.
internal Any member of a type, also any nested type The item is visible only within its containing assembly.
private Any types or members The item is visible only inside the type to which it belongs.
protected internal Any member of a type, also any nested type The item is visible to any code within its containing assembly and also to any code inside a derived type.

There are two types of inheritence implemented in C#. Implementation Inheritence and Interface Inheritence.

Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and functions. With implementation inheritance, a derived type adopts the base type’s implementation of each function, unless it is indicated in the definition of the derived type that a function implementation is to be overridden. This type of inheritance is most useful when you need to add functionality to an existing type, or where a number of related types share a significant amount of common functionality.

Interface inheritance means that a type inherits only the signatures of the functions but does not inherit any implementations. This type of inheritance is most useful when you want to specify that a type makes certain features available. Interface inheritance is often regarded as providing a contract: By deriving from an interface, a type is guaranteed to provide certain functionality to clients.

Imp: C# doesnot implement Multiple Inheritence i.e. you cannot inherit a class from more than one class.

By declaring a base class function as virtual, you allow the function to be overridden in any derived classes.

class MyBaseClass
{
   public virtual string VirtualMethod()
   {
      return “This method is virtual and defined in MyBaseClass and can be overridden in                   derievd class”;
   }
}

You use the override keyword when you write a new implementation of the virtual method in the derieved class.

public override string VirtualMethod() //this is the method which is overriden.

Neither member fields nor static functions can be declared as virtual.

Hiding Methods

If a method with the same signature is declared in both base and derived classes, but the methods are not declared as virtual and override, respectively, then the derived class version is said to hide the base class version.In these situations, C# generates a compilation warning. That reminds you to use the new keyword to declare that you intend to hide a method.

you can use the base.<MethodName>() syntax to call any method in the base class .

C# allows both classes and functions to be declared as abstract. An abstract class cannot be instantiated, whereas an abstract function does not have an implementation, and must be overridden in any non-abstract derived class. Obviously, an abstract function is automatically virtual (although you don’t need to supply the virtual keyword; doing so results in a syntax error).

C# allows classes and methods to be declared as sealed. In the case of a class, this means that you can’t inherit from that class. In the case of a method, this means that you can’t override that method.

Constructors in the hierarchy

If all the classes in the hierarchy have only default constructors then when u instantiate a class the control goes to the constructor of its immediate base class from there it goes to its immediate base class…like that till it reaches System.Object. Since System.Object doesnot have any base class…its constructor is executed…then its next derieved class’ cons is exec…till it reaches the cons of the class to be instantiated.

When you write your own constructors…stick to this principle.The base and this keywords are the only keywords allowed in the line that calls another constructor. Anything else causes a compilation error. Also note that only one other constructor can be specified.

We’ll take an example to understand this:

We have class called Employee it just has a field indicating the EmpId

class Employee
{
      private string empId;
      public Employee()
     {
      }
}

Then you have a class called ContractEmployee which is inherited from Employee and has an extra field of number of contract months.
class ContractEmployee: Employee
{
       private int contractMonths;
       public ContractEmployee():base()
      {
      }
}

In the above case when the class ContractEmployee is instantiated then the default cons of its base class is called and goes upto Object class. If you want to instantiate the employee field with employee id i.e if the user has to produce the employee id of the new emp while creating the class itself then the constructor of the Employee class takes a parameter and takes the following form

class Employee
{
      private string empId;
      public Employee(string id)
     {
          this.empId = id;
     }
}

Now when you instantiate the derieved class i.e the ContractEmployee class then you have to supply name to the emp…but that field is a private member of the base class. So what you have is sth like this:

class ContractEmployee: Employee
{
       private int contractMonths;
       public ContractEmployee(string id):base(id)
      {
      }
}

The derieved class has no way to implement this but the base class can do that so what the former does is to pass on the parameter to the base class cons.

Now the req is that the emp who referred to the conractemp should be saved in a field of referrer.

class ContractEmployee: Employee
{
       private int contractMonths;
       private string referrer;
       public ContractEmployee(string id,string refr):base(id)
      {
            this.referrer = refr
      }
}

But there may be some contract emp who have no referrers for them there would be no referrers. For them you should have a one parameter cons.Note how this is implemented….the derieved class now has two constructors with two parameters.

class ContractEmployee: Employee
{
       private int contractMonths;
       private string referrer;
       public ContractEmployee(string id,string refr):base(id)
      {
            this.referrer = refr
      }
     public ContractEmployee(string id):this(id,”none”)
      {      
      }

}

thi is how more than one constructors are implemented.When a contract emp with no ref is instantiated then cons with one param is called which in turns call the cons with 2 params giving the referrer as “none” then the base classes single param cons is called.

The syntax for a constructor is tht you declare a method that has the same name as the containing class and that does not have any return type:
public class MyClass
{
    public MyClass()
  {
  }
  // rest of class definition

if you don’t supply any constructor, the compiler will just make up a default one for you behind the scenes. It’ll be a very basic constructor that just initializes all the member fields by zeroing them out (null reference for reference types, zero for numeric data types, and false for bools).you can provide as many overloads to the constructor as you want, provided they are clearly different in signature.however, that if you supply any constructors that take parameters, the compiler will not automatically supply a default one. This is done only if you have not defined any constructors at all.

You can specify access specifiers for constructors. If you specify a constructor as private then it is impossible for that class to get instantiated. It is useful in couple of occasions such as:

  • If your class serves only as a container for some static members or properties and therefore should never be instantiated

  • If you want the class to only ever be instantiated by calling some static member function (this is the so-called class factory approach to object instantiation)

  • Static Constructor

    Static Constructor is the one that can be executed only once. It is exec only one time  unlike instance constructors which are exec for every instance.One reason for writing a static constructor is if your class has some static fields or properties that need to be initialized from an external source before the class is first used.

    The .NET runtime makes no guarantees about when a static constructor will be executed, so you should not place any code in it that relies on it being executed at a particular time (for example, when an assembly is loaded). Nor is it possible to predict in what order static constructors of different classes will execute. However, what is guaranteed is that the static constructor will run at most once, and that it will be invoked before your code makes any reference to the class. In C#, the static constructor usually seems to be executed immediately before the first call to any member of the class.

    the static constructor cannot ever take any parameters, and there can only be one static constructor for a class. It should also be obvious that a static constructor can only access static members, not instance members, of the class.It can’t hav any access modifiers.Note that it is possible to have a static constructor and a zero-parameter instance constructor defined in the same class.Note that if you have more than one class that has a static constructor, the static constructor that will be executed first is undefined.

    public MyClass(string description) : this(model, 4)
       {
       }

    the this keyword allows us to call the constructor in the same class with the matchin signature.It will be the first constructor to get execueted and then the remaining code of the callin constructor is executed. If you use base keyword then it will call the matchin constructor of the base class.

    Syntax for the properties is
    [modifier] return_type PropertyName
    {
             get
            {
                  //return value
            }
             set
           {
             //do set the val here…
           }
    }

    The get accessor takes no parameters and must return the same type as the declared property. You should not specify any explicit parameters for the set accessor either, but the compiler assumes it takes one parameter, which is of the same type again, and which is referred to as value.
    It is possible to create a read-only property by simply omitting the set accessor from the property definition.
    It is similarly possible to create a write-only property by omitting the get accessor.

    The get and set accessor can have different access modifiers

    public string ExProperty
    {
             get
            {
                  //return value
            }
             private set
           {
             //do set the val here…
           }
    }

    Here the set accessor has private accessibility. Atleast one should have access modifier of the Property. Here if the scope of get were to be Protected then it would have resulted in a compile error.

    The syntax for declaring a method is

    [modifiers] return_type MethodName([parameters])
    {
          //Method body…
    }

    Arguments can in general be passed into methods by reference or by value.When a variable is passed by reference, the called method gets the actual variable – so any changes made to the variable inside the method persist when the method exits. On the other hand, if a variable is passed by value, the called method gets an identical copy of the variable – which means any changes made are lost when the method exits.

    Passing variables by value is the default. You can, however, force value parameters to be passed by reference. To do so, you use the ref keyword.

    int exMethod(int[] intarr, ref int i)
    {
           intarr[0] = 10; // The change to i will persist after exMethod() exits.
           i = 20;
    }

    Adding the ref keyword in C# serves the same purpose as using the & syntax in C++ to specify passing by reference.Any variable must be initialized before it is passed into a method, whether it is passed in by value or reference.

    You need to initialise all the variables before using them and this is valid for parameters.. to avoid doing that we can use out keyword to send in the var that is not yet initialised

    static void exMethod(out int i)
    {
       p= 10;
    }

    public static int Main()
    {
       int p; // note how i is declared but not initialized.
       exMethod(out p);
       Console.WriteLine(p);
       return 0;
    }

    Overloading

    C# supports method overloading – several versions of the method that have different signatures (that is, the name, number of parameters, and parameter types).

    C# does not support default parameters in the way that, say, C++ or Visual Basic does.

    The following care should be taken for overloading methods:

  • It is not sufficient for two methods to differ only in their return type.

  • It is not sufficient for two methods to differ only by virtue of a parameter having been declared as ref or out.

  •  A Class and an Object are like egg and hen… which would have come out first?… The class is a blue print of an object and we can design a class only if we hav the object with us…

    Class is a template for an object.. you instantiate a class to create an object its like you give flesh and skin to a skeleton… :-)

    Structs differ from classes in the way that they are stored in memory and accessed (classes are reference types stored in the heap, structs are value types stored on the stack), and in some of the features (for example, structs don’t support inheritance).

    For both classes and structs, you use the keyword new to declare an instance: This keyword creates the object and initializes it.

    Data members are those members that contain the data for the class – fields, constants, and events.Data members can be either static (associated with the class as a whole) or instance (each instance of the class has its own copy of the data).

    Fields are any variables associated with the class.

    Function members are those members that provide some functionality for manipulating the data in the class. They include methods, properties, constructors, finalizers, operators, and indexers.

    In Visual Basic, C, and C++, you could define global functions that were not associated with a particular class. This is not the case in C#. As noted earlier, in C# every function must be associated with a class or struct.

    official C# terminology does in fact make a distinction between functions and methods. In this terminology, the term “function member” includes not only methods, but also other nondata members of a class or struct. This includes indexers, operators, constructors, destructors, and also – perhaps somewhat surprisingly – properties. These are contrasted with data members: fields, constants, and events.

    Structs are similar to Classes but are more useful where we just need to group some data and dont require all the flexibility of the classes thus reducing the performance head.

    They differ from classes in the following ways:

    • Structs are value types, not reference types. This means they are stored either in the stack or inline (if they are part of another object that is stored on the heap) and have the same lifetime restrictions as the simple data types.

    • Structs do not support inheritance.

    • There are some differences in the way constructors work for structs. In particular, the compiler always supplies a default no-parameter constructor, which you are not permitted to replace.

    • With a struct, you can specify how the fields are to be laid out in memory. 

    Structs follow the same rules as any other data type: everything must be initialized before use.

    You can define constructors for structs in exactly the same way that you can for classes, except that you are not permitted to define a constructor that takes no parameters.

    struct Dimensions
    {
       public double Length = 1;       // error. Initial values not allowed
       public double Width = 2;        // error. Initial values not allowed
    }

    Partial Classes are classes which span across multiple files…which on compilation become one…this helps if more people work on a single class..

    if you don’t specify a base class when you define a class, the compiler will automatically assume that it derives from Object. It means that in all you classes you also have the methods which are present in the Object class. The diff methods in the Object class are:

    string ToString()
     public virtual
     Returns a string representation of the object
     
    int GetHashCode()
     public virtual
     Used if implementing dictionaries (hash tables)
     
    bool Equals(object obj)
     public virtual
     Compares instances of the object for equality
     
    bool Equals(object objA, object objB)
     public static
     Compares instances of the object for equality
     
    Type GetType()
     Public
     Returns details of the type of the object
     
    object MemberwiseClone()
     Protected
     Makes a shallow copy of the object
     
    void Finalize()
     protected virtual
     This is the .NET version of a destructor

    To compile files other than .exe we have to use different compiler options…. for that we have to use /t or /target  switch… for eg to compile a library /t:library example.cs the compiler will compile this into a dll…

    The exhaustive list of compiler options can be seen here.

    XML Documentation

    C# is the only language which provides us the facility for xml documentation. We can tell the compiler about the xml documentation while compiling with the /doc tag.

    To make xml documentation possible we have to comment using /// instead of //.

    All the tags and info regd. the documentation is available here.

    Casing

    There are two types of casings which are recommended for use in C#. They are PascalCasing and camelCasing.

    Camel casing is recommended for the following names:

    • For names of all private member fields in types.
    • For names of all parameters passed to methods.
    • To distinguish items that would otherwise have the same name. A common example is when a property wraps around a field.

    Pascal casing is used for remaining names.

    • Value types store the value and copying it another variable makes two copies of that whereas in reference types the 2 variables will be referencing to the same value so changes made to one variable will also reflect in other.

    • Value types are allocated on stack and reference types on managed heap.

    • Decimal datatype is not implemented as primitive type so using it eill have performance impact.

    • C# char is of 2 bytes as compared to C++ char which is of 1 byte.

    • strings can be assigned using ‘=’ ign but they are reference types.when I copy one string to another variable they both refer to the same string but when modified, another copy is created and both variables contain different strings.This happens because of “operator overloading”.

    • Enumerations are of integer type. They are instantiated as ’structs’, so i can run many methods over my enums and there is no performance loss. Once compliled the enums exist as primitive types just like int or float.

    • I can obtain the string value of enum for eg. TimeOfDay time
      time = TimeOfDay.Afternooh; writeline(Afternoon.ToString())

    • Also i can obtain the enum value from the string
      TimeOfDay time2 = (TimeOfDay)Enum.Parse(typeof(TimeOfDay),Afternoon,true);writeline((int)time2)…op will be int value of Afternoon.

    • Arrays syntax int[] var = new int[5]; Arrays are reference types.Zero based indexing is followed.

    • Setting Aliases to the namespaces using alias  = namespace; to instantiate a class use the namespace alias qualifier :: eg.alias::classname

    • If the program contains more than one Main(). I can tell the compiler to use a specific main by using /main switch , together with full name of the class including the namespace to wich the main belongs. eg, csc Hello.cs /main:namespace.class

    • Parameters can be passedto the Main method…then the Main syntax will be  public static int Main(string[] args)

    • to compile the file to a class library from a console window i can use the /target switch to tell which type to be compiled to.eg. /t:exe to a console app, /t:library, to a classlibrary.

    • /out can be used to mention the output file name. To reference any class library in console app use /r sritch. eg asa hello.cs /r:Math.dll.

    • Preprocessor statements help in debugging…#define…#undef, tell the compiler that a symbol exists and only if the smbol exists then…#if symbol…

    If…then…else

    If then else is a condtional statement where if condition is true then then clause is executed or else clause is executed

    if(condition)
    {
         //statements;
    }
    else
        //statements;
    }

    In C#, the expression in the if clause must evaluate to a Boolean.

    Switch

    The switch…case statement is good for selecting one branch of execution from a set of mutually exclusive ones.When the expression in the switch argument evaluates to one of the values beside a case clause, the code immediately following the case clause executes. This is one example where you don’t need to use curly braces to join statements into blocks; instead, you mark the end of the code for each case using the break statement. You can also include a default case in the switch statement, which will execute if the expression evaluates to none of the other cases.the case values must be constant expressions; variables are not permitted.

    if a case clause is fired early on in the block, later clauses cannot be fired unless you use a goto statement to mark that you want them fired, too. it means the break statement is mandatory…

    There is one exception to the no-fall-through rule, however, in that you can fall through from one case to the next if that case is empty. This allows you to treat two or more cases in an identical way (without the need for goto statements).

    The order of the cases doesn’t matter.

    The For Loop

    The C# for loop is for iterating a set of statements for a set of times depending on the condition.

     (initializer; condition; iterator)
        statement(s)

    where

    • The initializer is the expression evaluated before the first loop is executed (usually initializing a local variable as a loop counter).

    • The condition is the expression checked before each new iteration of the loop (this must evaluate to true for another iteration to be performed).

    • The iterator is an expression evaluated after each iteration (usually incrementing the loop counter). The iterations end when the condition evaluates to false.

    The while Loop

    The while loop is identical to the while loop in C++ and Java, and the While…Wend loop in Visual Basic. Like the for loop, while is a pretest loop. The syntax is similar, but while loops take only one expression:

     while(condition)   statement(s);
     

    Unlike the for loop, the while loop is most often used to repeat a statement or a block of statements for a number of times that is not known before the loop begins.

    The do . . . while Loop

    The do…while loop is the post-test version of the while loop. It does the same thing with the same syntax as do…while in C++ and Java, and the same thing as Loop…While in Visual Basic. This means that the loop’s test condition is evaluated after the body of the loop has been executed. Consequently, do…while loops are useful for situations in which a block of statements must be executed at least one time.

    bool condition;
    do
    {
       // This loop will at least execute once, even if Condition is false.
       MustBeCalledAtLeastOnce();
       condition = CheckCondition();
    } while (condition);

     

    The foreach Loop

    The foreach loop allows you to iterate through each item in a collection.

    foreach (int temp in arrayOfInts)
    {
       Console.WriteLine(temp);
    }

    The goto Statement

    The goto statement allows you to jump directly to another specified line in the program, indicated by a label (this is just an identifier followed by a colon):

     goto Label1;    Console.WriteLine("The control doesn't reavh here...");
    Label1:    Console.WriteLine("instead control strts executing frm here...");

    Some restrictions are there for using goto statement..

    • You can’t jump into a block of code such as a for loop.

    • you can’t jump out of a class, and you can’t exit a finally block after try…catch blocks

    There is one place where it is quite handy: jumping between cases in a switch statement, particularly because C#’s switch is so strict on fall-through.

    The break Statement

    When you use the break statement the control reaches the statement immediately after the end of the loop…If the statement occurs in a nested loop, control will switch to the end of the innermost loop.

    The continue Statement

    The continue statement is similar to break, and must also be used within a for, foreach, while, or do…while loop. However, it exits only from the current iteration of the loop, meaning that execution will restart at the beginning of the next iteration of the loop, rather than outside the loop altogether.

    The return Statement

    The return statement is used to exit a method of a class, returning control to the caller of the method. If the method has a return type, return must return a value of this type; otherwise if the method returns void, you should use return without an expression.

    C# implements string as a class which encapsulates many a functionaltity which makes life much easier.

    String is a reference type…if you equate 2 string objects they point to the same value… but the catch here is tht if you change any one then it will create a complete new object leaving the other unchanged.

    String literals are enclosed in double quotation marks (“…”);

    Because these escape sequences start with a backslash, you can’t use this character unescaped in a string. Instead, you need to escape it with two backslashes (\\):          string filepath = “C:\\Windows\\example.cs”;

    You can prefix a string literal with the at character (@) and all the characters in it will be treated at face value; they won’t be interpreted as escape sequences:

    string filepath = @”C:\Windows\example.cs”;

    Will Update later…

    Next Page »