Friday, 26 August 2011

Operator Overloading


                 By the using Operator overloading we can do the arithmetic operation on the user define data types as class, structures. Do any operation symbolizing the operator in your class.
You can add/subtract/multiply/divide or do any other operation for  + operator() the choice is entirely yours.

The following Program describes about Operator Overloading...



public class Complex
    {
        public int real;
        public int imaginary;

        public Complex(int real, int imaginary)
        {
            this.real = real;
            this.imaginary = imaginary;
        }

        // Declare which operator to overload (+), the types
        // that can be added (two Complex objects), and the
        // return type (Complex):
        public static Complex operator +(Complex c1, Complex c2)
        {
            return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
        }
        // Override the ToString method to display an complex number in the suitable format:
        public override string ToString()
        {
            return (String.Format("{0} + {1}i", real, imaginary));
        }

        public static void Main()
        {
            Complex num1 = new Complex(2, 3);
            Complex num2 = new Complex(3, 4);

            // Add two Complex objects (num1 and num2) through the
            // overloaded plus operator:
            Complex sum = num1 + num2;

            // Print the numbers and the sum using the overriden ToString method:
            Console.WriteLine("First complex number:  {0}", num1);
            Console.WriteLine("Second complex number: {0}", num2);
            Console.WriteLine("The sum of the two numbers: {0}", sum);
            Console.Read();

        }
    }

Output:

First complex number:  2 + 3i
Second complex number: 3 + 4i
The sum of the two numbers: 5 + 7i






Private Constructor


When you declare a Constructor with Private access modifier then it is called Private Constructor. We can use the private constructor in singleton pattern.

If you declare a Constructor as private then it doesn't allow to create object for its
derived class, i.e you loose inherent facility for that class.

In the following program I'm trying to create a derived class  for the Base class having Private constructor it shows an error like .
   Error: parent()  is inaccessible due to its protection level   
Use public instead of private then  the following program works...



class parent
    {
       public  string name;
       private   parent()
       //use public instead of private then this program works...
        {
            this.name = "Radha";
        }
    }

    class child : parent
    {
        public void show()
        {
            Console.WriteLine(name);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            child obj = new child();
            obj.show();
            Console.Read();

        }
    }
}


// Error :: parent()' is inaccessible due to its protection level  

Order of Constructor execution in Inheritance

  •  constructors are called in the order from the top to the bottom (parent to child class) in inheritance hierarchy.
See the below program and check the output ...




class parent
    {
        public parent()
        {
            Console.WriteLine("This is Paarent");
        }
    }
    class child : parent
    {
        public child()
        {
            Console.WriteLine("This is child");
        }
    }

    class Program : child
    {
        static void Main(string[] args)
        {
            Program obj = new Program();
            Console.Read();

        }

        public Program()
        {
            Console.WriteLine("This is program");
        }
    }


Output:

This is Paarent
This is child
This is program

Shadowing and Overriding differences using Static keywords...

 In this blog i  already specified about Shadowing concept . if you don't know then check it once.
  • Here the following program describes the differences between shadowing and overriding what i observe are written below the program





 class A
    {
        public virtual  void methodsample()
        {
            Console.WriteLine("methodsample in A");
        }
        public void methodOne()
        {
            Console.WriteLine("methodOne in A");
        }
        public  void methodTwo()
        {
            Console.WriteLine("methodTwo in A ");
        }
        public  static  void methodThree()
        {
            Console.WriteLine("methodThree in A");
        }
        public static void methodFour()
        {
            Console.WriteLine("methodFour in A");
        }
    }
    class B : A
    {
        public override void methodsample()
        {
            Console.WriteLine("methodsample in A overridding...This is methodsample in class B");
        }

        public new void methodOne()
        {
            Console.WriteLine("methodOne in B ");
        }
        public new static void methodTwo()
        {
            Console.WriteLine("methodTwo in B");
        }
        public new static  void methodThree()
        {
            Console.WriteLine("methodThree in B");
        }
        public new void methodFour()
        {
            Console.WriteLine("methodFour in B");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            A obj = new A();
            obj.methodsample();
            A objA = new B();  // observe in creating instance....
            objA.methodsample();
            objA.methodOne();
            objA.methodTwo();
            A.methodThree();
            A.methodFour();
            //objB.methodFour(); bcz static methods cannot acess with object name
            B objB = new B();
            objB.methodOne();
            B.methodTwo();
            B.methodThree();
            objB .methodFour();
            objB.methodsample();
            //objB.methodTwo(); static method ...
            Console.ReadLine();
        }
    }

Points I observed:
/* for this program no method can be overriden . Here Just Shadowing concept will be takes place only.
   the flow is like : for which class you create object those methods only will be executed .
   Try to comment  methodOne and methodFour in class B and create object for B and Execte that...
   for methodFour it shows an error...bcz we cannot shadow static methods...
  comment methodTwo in classB and observe...
  static methods can only call with class names .with what class name you are calling that method will be        executed.
  A obj = new B(); is possible.
  B obj = new A(); Not possible. bcz A is parent class....
  If you use new keyword in derived class then it doesn't show any warning means it hides the base class method and this concept is known as shadowing ...
 Here u observe the difference between overriding and shadowing...
 Observe commenting ovverride methodsample in class B and execute...*/

Output:

methodsample in A
methodsample in A overridding...This is methodsample in class B
methodOne in A
methodTwo in A
methodThree in A
methodFour in A
methodOne in B
methodTwo in B
methodThree in B
methodFour in B
methodsample in A overridding...This is methodsample in class B


Copy Constructor in C#

         Unlike some languages, C# does not provide a copy constructor. If you create a new object and want to copy the values from an existing object, you have to write the appropriate method yourself.

The following program describes copy constructor...

 class sample
    {
        string nme;
        int number;

        public sample()
        {
       
        }
       
        // Parameterised Constructor.............
        public sample(string name, int no)
        {
            this.nme = name;
            this.number = no;
        }
        // Copy Constructor -------------------------
        public sample (sample object11)
        {
            nme=object11.nme;
            number = object11.number;
           
   
        }

        public void show()
        {
            Console.WriteLine("Name is " + nme);
            Console.WriteLine("Number is " + number);
        }
    }
   
   
   
    class Program
    {
        static void Main(string[] args)
        {
            sample obj = new sample("radha",101);
            sample obj1 = new sample(obj);
            obj.show();
            obj1.show();
            Console.Read();


        }
    }


Output:
Name is radha
Number is 101
Name is radha
Number is 101


Thursday, 25 August 2011

Static Constructors

    A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

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 static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

    The following Program describes about the static constructor...



class sample
    {
         public static int i;
         public int j;
         static sample()
        {
            i = 10;
            //j = 11; Error:: An object reference is required for the non-static field, method, or property .

            Console.WriteLine("static constructor is invoked");
        }

        public sample()
        {
            int j = 22;
            Console.WriteLine("Non Static Constructor is invoked");
        }
           
    }

                                                     

    class Program
    {
      
        static void Main(string[] args)

        {
            Console.WriteLine("i value is " + sample.i);
         // Static constructor is called before object creation.
            sample obj = new sample();
            Console.WriteLine("J value is " + obj.j);
            Console .Read();

        }
    }

Output:
static constructor is invoked
i value is 10
Non Static Constructor is invoked
J value is 0





Message Passing in Object Oriented Programming


              Message passing is a method by which an object sends data to another object or requests other object to invoke method. This is also known as interfacing. It acts like a messenger from one object to other object to convey specific instructions.

The following Program explains about the message passing...




class Base
    {
        public Base()
        { }
        public Base(string s)
        {
            Console.WriteLine("hi " +s);
        }
    }
    class Derived : Base
    {
       
        public Derived(string s)
        {
            Base b = new Base(s);
            Console.WriteLine(s);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Derived d = new Derived("Krishna");
            Console.ReadLine();
        }
    }

Output:

hi Krishna
Krishna

// Here Object d invokes the Constructor of base class that means object interaction will be takes place between Object d and Object b.


Partial Class

      When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.To split a class definition, use the partial keyword modifier.
  • Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace. All the parts must use the partial keyword. All of the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public, private, and so on.
  • If any of the parts are declared abstract, then the entire type is considered abstract. If any of the parts are declared sealed, then the entire type is considered sealed. If any of the parts declare a base type, then the entire type inherits that class.
The following Program describes about Partial classes..



public  partial class coords //use abstract and check...
    {
        private int x;
        private int y;

        //public coords() { }
        public coords(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

    public partial class coords
    {
        public void PrintCo()
        {
            System.Console.WriteLine("CoOrds: {0},{1}", x, y);
        }

    }

    class Program //:coords
    {
        static void Main()
        {
            coords obj = new coords(10, 15);
           // Program obj = new Program();
            obj.PrintCo();
            Console.Read();
        }
    }

Output:
CoOrds: 10,15


Shallow Copy and Deep Copy


      A shallow copy creates a new instance of the same type as the original object, and then copies the non-static fields of the original object.
The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the non static fields of the current object to the new object. If the field is a value type, a bit-by-bit copy of the field is performed. If the field is a reference type, the reference is copied but the referred object is not; 
Simply saying, shallow copy copies the structure of the object, deep copy copies structure as well as data
In a deep copy, all objects are duplicated; whereas, in a shallow copy, only the top-level objects are duplicated and the lower levels contain references..

          
For example, consider an object called X that references objects A and B. Object B, in turn, references object C. A shallow copy of X creates new object X2 that also references objects A and B. In contrast, a deep copy of X creates a new object X2 that references the new objects A2 and B2, which are copies of A and B. B2, in turn, references the new object C2, which is a copy C. Use a class that implements the ICloneable interface to perform a deep or shallow copy of an object.

The following program will explain ...



namespace shallowcopyingexpl
{
  
public class IdInfo
    {
        public int IdNumber;

        public IdInfo(int IdNumber)
        {
            this.IdNumber = IdNumber;
        }
    }

    public class Person
    {
        public int Age;
        public string Name;
        public IdInfo IdInfo;

        public Person ShallowCopy()
        {
            return (Person)this.MemberwiseClone();
        }

        public Person DeepCopy()
        {
            Person other = (Person)this.MemberwiseClone();
            other.IdInfo = new IdInfo(this.IdInfo.IdNumber);
            return other;
        }
    }

    public class Example
    {
        public static void Main()
        {
            // Create an instance of Person and assign values to its fields.
            Person p1 = new Person();
            p1.Age = 42;
            p1.Name = "Sam";
            p1.IdInfo = new IdInfo(6565);

            // Perform a shallow copy of p1 and assign it to p2.
            Person p2 = (Person)p1.ShallowCopy();

            // Display values of p1, p2
            Console.WriteLine("Original values of p1 and p2:");
            Console.WriteLine("   p1 instance values: ");
            DisplayValues(p1);
            Console.WriteLine("   p2 instance values:");
            DisplayValues(p2);

            // Change the value of p1 properties and display the values of p1 and p2.
            p1.Age = 32;
            p1.Name = "Frank";
            p1.IdInfo.IdNumber = 7878;
            Console.WriteLine("\nValues of p1 and p2 after changes to p1:");
            Console.WriteLine("   p1 instance values: ");
            DisplayValues(p1);
            Console.WriteLine("   p2 instance values:");
            DisplayValues(p2);

            // Make a deep copy of p1 and assign it to p3.
            Person p3 = p1.DeepCopy();
            // Change the members of the p1 class to new values to show the deep copy.
            p1.Name = "George";
            p1.Age = 39;
            p1.IdInfo.IdNumber = 8641;
            Console.WriteLine("\nValues of p1 and p3 after changes to p1:");
            Console.WriteLine("   p1 instance values: ");
            DisplayValues(p1);
            Console.WriteLine("   p3 instance values:");
            DisplayValues(p3);
            Console.Read();
        }

        public static void DisplayValues(Person p)
        {
            Console.WriteLine("      Name: {0:s}, Age: {1:d}", p.Name, p.Age);
            Console.WriteLine("      Value: {0:d}", p.IdInfo.IdNumber);
        }
    }

}

//changes in one object doesn't reflect the other object .just structure only copied from one object to other not data.

Output:
Original values of p1 and p2:
   p1 instance values:
      Name: Sam, Age: 42
      Value: 6565
   p2 instance values:
      Name: Sam, Age: 42
      Value: 6565

Values of p1 and p2 after changes to p1:
   p1 instance values:
      Name: Frank, Age: 32
      Value: 7878
   p2 instance values:
      Name: Sam, Age: 42
      Value: 7878

Values of p1 and p3 after changes to p1:
   p1 instance values:
      Name: George, Age: 39
      Value: 8641
   p3 instance values:
      Name: Frank, Age: 32
      Value: 7878



Wednesday, 24 August 2011

Shadowing in .Net


Shadowing hides a method in a base class.

We can achieve shadowing in C#  using  new  keyword .

  • If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.
  •  If the new keyword is not specified in the derived class , the compiler will issue a warning and the method in the derived class will hide the method in the base class.
The following program describes about the shadowing ...
 



public class clsA
    {
        public  void Foo() { Console.WriteLine("This is Base class A"); }
        public virtual void Bar() { Console.WriteLine("This is Base class A with virtual"); }
        public virtual void ss(){Console.WriteLine("Hiiiiiiiiiiiiiii");}
    }
    class clsB : clsA
    {
        public new void Foo() { Console.WriteLine("This is Child Class B"); }
        public override void Bar() { Console.WriteLine("this is Child class B override"); }
        public new void ss() { Console.WriteLine("Byeeeeeeeeeeeeeeee"); }
    }

   
    class Program
    {
        static void Main(string[] args)
        {
            clsA obj = new clsA();
            obj.Foo();
            obj.Bar();
            obj.ss();

           clsB obj1 = new clsB();
            obj1.Foo();
            obj1.Bar();
            obj1.ss();

            clsA obj2 = new clsB();
            obj2.Foo();
            obj2.Bar();
            obj2.ss();


            Console.ReadLine();
        }
    }



/* if you don't use new key word in Child class B then compiler shows an warning that for hiding use new keyword.
  By using New keyword it hides the base class method this is called Shadowing.
  use static keyword in Base and Derived classes and check once...
  Comment the method Bar() in derived class B and check it once...*/

Output:
 
This is Base class A
This is Base class A with virtual
Hiiiiiiiiiiiiiii

This is Child Class B
this is Child class B override
Byeeeeeeeeeeeeeeee

This is Base class A
this is Child class B override
Hiiiiiiiiiiiiiii

Constans and Readonly Keywords

Constants:
        Constants are values which are known at compile time and do not change. (To create a constant value that is initialized at runtime, use the readonly keyword.) Constants are declared as a field, using the const keyword before the type of the field.
  • A constant variable should have value at design time. 
  • All the constant variables are static ie they are shared across all the instances of the class. You dont have to add the keyword "static".
  • Constants are copied to all the dlls where is refereeing the parent class ie even if you change the the original constant value and recompile the parent dll , the other dll will still use the old value. The size of the executable goes up since all these constants are copied to the respective dlls
  • Constant variables can be called with Class name only. 
 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.
  • We cannot modify the readonly values outside the constructor or variable initializer. 


I think the following example program helps you to find the differences between Constant and Readonly





class MyClass
        {
            public int x;
            public int y;
            public const  int c1=100;
            public readonly int c2;//c2=some value  is also acceptable..

            public MyClass(int p1, int p2)
            {
                x = p1;
                y = p2;
               // c1 = p1 + p2; Generates error because we can't modify the constant variables...
                c2 = p1 + p2;
                c2 = c2 + 100; // some changes to readonly for better understanding...
                //c1= 10; then error occurs...
            }


             public void modify()
            {
                //c2 = c2 + 200;    Error :: A readonly field cannot be assigned to (except in a constructor or a variable initializer)   
                Console.WriteLine("c2 value after trying to modify:"+c2 );
            }
        }

        class program
        {
            public static void Main()
            {
                MyClass obj = new MyClass(11, 22);
                obj.x = 155;  //acceptable bcz normal variable...
                //obj.c2 = 55; generates an error this is the use of readonly...After creating the instance we cannot modify the readonly variables...
                Console.WriteLine("x = {0}, y = {1}", obj.x, obj.y);
                Console.WriteLine("c1 = {0}, c2 = {1}", MyClass .c1, obj.c2);//calling const c1 with its class name...and Readonly with Object Name.
                Console.ReadLine();
            }

        }
// Constant variables can be initialized at the time of declaration only whereas readonly initialized At declaration or any where.
// Constant variables can be called with class name only...but readonly can be  called with object name only...


Output: 
           x = 155, y = 22
          c1 = 100, c2 = 133

          c2 value after trying to modify :133