Wednesday, November 25, 2009

C# constructors

  1. Static constructor
  2. Instance constructor (non-static constructor)



Static constructor
  • Does not take access modifiers
  • Cannot access any non static members
  • Static constructor will get called as soon as we create an instance of the class or we refer the class
  • class which implements static constructor does not has to be static.
  • static constructor calls only once.
  • it can be used for initializing objects
    eg, say there is an employee class, and we want to know how many employee object's are created. This case you can create a static integer variable and increment the count.





Tuesday, November 24, 2009

C# 3.0 features

  1. 3.0 allows properties without local variables
  2. var  (varient) - it is implicitly typed variable
  3. Anonymous variable
  4. Lamda expression
  5. FUNC<>
  6. Extention Method

Here is the detail:

1. C#3.0 allows properties without local variables: 
Tip: Type prop in the visual studio and press tab
 2.  Simple and implicitly typed local variable

  • It is implicitly typed variable
  • var i=10;
  • var str="nidhish";
  • var x="109"; // It is invalid. Compiler does not allow this.
  • var CANNOT be used as a parameter or a return type. It is heavily used in LINQ
3. Anonymous variable:

  • it is helpful for object initialization
  • Example:
List mystring=new List {
  "Item1",
  "Item2",
  "Item3"}
4. Lamda expression:

  • Example:
delegate long myadd(int n1,int n2);
Public void TestLamda()
{
   myadd ad= (n1,n2) => { return n1+n2; };
   Console.WriteLine(ad.invoke(100,150));
}

5. Extending type with extension method

Extension method provide developers to extend the functionality of an existing type. Extension methods are static methods with keywork this

Eg: Extend string class with a reverse method

    Saturday, November 21, 2009

    Order of execution of Catch statements

    • System.Exception is the base class for Exceptions
    • System.Exception should be the last catch block.
    • Catch block for all the child exceptions should be declared before System.Exception. Compiler throws exception if the order is not following.

    •  Sample (WRONG)

                try
                {
                    int c= 10/0;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception block:" + ex.Message);
                }
                catch (DivideByZeroException dex)
                {
                    Console.WriteLine("DivideByZeroException block:" + dex.Message);
                }
    COMPILE ERROR: A previous catch clause already catches all exceptions of this or of a super type ('System.Exception')

    • Sample (CORRECT)
                 try
                {
                    int c= 10/0;
                }
                catch (DivideByZeroException dex)
                {
                    Console.WriteLine("DivideByZeroException block:" + dex.Message);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception block:" + ex.Message);
                }


    Eg : Another Sample

    Singleton pattern

    • Class will have only one instance
    • And there will be a global point to access it


    Reference: 


    http://www.dofactory.com/Patterns/PatternSingleton.aspx

    How to implement singleton?
    1. Create private constructor for CLASS
    2. Declare a static member of the CLASS
    3. Declare a static property , in which new object of CLASS creates if it does not exist.
    Sample:

    class Singleton
    {
        private static Singleton instance;

        private Singleton() {}

        public static Singleton Instance
        {
            get
                {
                    if(instance ==null)
                    {
                        instance= new Singleton();
                    }
                    return instance;
                }
        }
    }

    class TestSingleton
    {
        private TestSingleton()
        {
        }

        public static void DoTest()
        {
            ////Singeleton
            Singleton obj1 = Singleton.Instance;
            Singleton obj2 = Singleton.Instance;

            // Test for same instance
            if (obj1 == obj2)
                System.Console.WriteLine("both instances are same!");
        }
    }

    Friday, November 20, 2009

    Deep copy and Shallow copy

    Shallow Copy

    • Shallow copy creates new object
    • Then copy all non static fields to the new object
    • System.Object.MemberwiseClone() method creates shallow copy of object
    Deep Copy
    • Deep copy creates new object
    • Then copy all feilds to the new object
    • Deep copy of an object can be created using Serialization
    • Mark the target class as [Serializable]
     
    References:

    1. MemberWiseClone - (shallow copy)
    Scenario: (C#.NET) There is an Employee class, which has 2 properties, ID & Name. There is an Employee class object E1. I want to create Shallow copy to E2 & Deep copy to E3. How?


     [Serializable]
        public  class Employee : ICloneable
        {
            private int id;
            private string name;

            public int ID
            {
                get { return id; }
                set { id = value; }
            }

            public string Name
            {
                get { return name; }
                set { name = value; }
            }

            public Employee ShallowCopy()
            {
                //shallow copy
                return (Employee)this.MemberwiseClone();
            }

            #region ICloneable Members

            public object Clone()
            {
                //deep copy
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                bf.Serialize(ms, this);
                ms.Position = 0;
                object obj = bf.Deserialize(ms);
                ms.Close();
                return obj;
               
            }

            #endregion
        }

        class DeepShallowSample
        {

            public DeepShallowSample()
            {
                Employee e1 = new Employee();
                e1.ID = 162;
                e1.Name = "Nidhish";
                Console.WriteLine(e1.GetHashCode());
               
                //Shallow copy
                Employee e2 = e1.ShallowCopy();
                Console.WriteLine(e2.GetHashCode());

                //Deep copy
                Employee e3 = (Employee)e1.Clone();  
                Console.WriteLine(e3.GetHashCode());   

               
            }
           
         
        }

    Wednesday, November 18, 2009

    Interface vs Abstract class

    1. When to go with Interfaces and how when to go with Abstract class?
    2. Can Interface contain properties?
    3. Can we do Interface1:Interface2?
    4. If yes, How does it implement in a class?
    5. Can an abstract class implement an Interface?

    http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx


    FeatureInterfaceAbstract class
    Multiple inheritanceA class may inherit several interfaces.A class may inherit only one abstract class.
    Default implementationAn interface cannot provide any code, just the signature.An abstract class can provide complete, default code and/or just the details that have to be overridden.
    Access ModfiersAn interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as publicAn abstract class can contain access modifiers for the subs, functions, properties
    Core VS PeripheralInterfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.An abstract class defines the core identity of a class and there it is used for objects of the same type.
    HomogeneityIf various implementations only share method signatures then it is better to use Interfaces.If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
    SpeedRequires more time to find the actual method in the corresponding classes.Fast
    Adding functionality (Versioning)If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
    Fields and ConstantsNo fields can be defined in interfacesAn abstract class can have fields and constrants defined



      Tuesday, November 17, 2009

      Runtime polymorphism vs Compile time polymorphism

       Polymorphism can be achieved in 3 ways:

      1. Method overloading     (compile time polymorphism
      2. Method overriding through inheritance (runtime polymorphism)
      3. Method overriding through C# interface (runtime polymorphism)
      Runtime polymorphism means, compiler would come to know which method to execute, at runtime not compile time. We can implement the runtime polymorphism by using override keyword.

      Late binding
      • The decision as to which version of method to invoke cannot be made at compile time.
      • It has to be done at run-time.
      • This is reffered as late binding


      Reference:

      http://www.dickbaldwin.com/csharp/Cs000120.htm


      Difference between compile time & run time polymorphism:

      • override functions have same signatures, but implemented in different classes
      • overload is function with same name but different signatures in same class


      Thursday, November 12, 2009

      custom control Vs user control

      • What is difference between custom control vs user control?

      Custom controlUser control
      Are compiled and distributed in binary format.ascx
      Custom control provide strong design time supportLimited design time support
      Control authors must create their own classes which sub class from System.UI.ControlRelatively easy to create
      Once compiled custom control can be added to toolbox and can be used same way as any .net controlUser controls are represented by placeholder
      Properties can set via property windowProperties cannot set by property window

      Anonymous method

      • Anonymous method
      - Its a .net 2.0 feature
      -We can create nameless methods, which can be called using delegates
      • Why Anonymous methods?
       In some cases we are forced to create a class or method just for the sake of using delegates. We can avoid it using anonymous method.


      Real time example:

      • Button click event implementation in windows form is handled using anonymous method:

                  //
                  // button1
                  //
                  this.button1.Location = new System.Drawing.Point(38, 116);
                  this.button1.Name = "button1";
                  this.button1.Size = new System.Drawing.Size(75, 23);
                  this.button1.TabIndex = 0;
                  this.button1.Text = "button1";
                  this.button1.UseVisualStyleBackColor = true;
                  //this.button1.Click += new System.EventHandler(this.button1_Click);

                  this.button1.Click += delegate(object sender, System.EventArgs e)
                  {
                      System.Windows.Forms.MessageBox.Show("Invoked using anonymous method!!"); 
                  };

      String vs StringBuilder

      • String vs StringBuilder
      String
      - Immutable
      - Every time a change happens in string, a new object is getting created in memory
      - In situation, you need to make repeated modification to string, its an overhead.


      System.Text.StringBuilder
      - Mutable
      - Advantage: Performance boost while doing string concatanation(use Append method)