Tuesday, July 12, 2011

How to Revise Basic OOPs concepts in C Sharp.Net (Summary only)

RAM RAM Friends

How to Revise Basic OOPs concepts in C Sharp.Net (only syntax and concepts but very less or no description) ) like (types of Constructors,Inheritance,Polymorphism,Abstract Class,Interface,Delegate,Events,Sealed Classes,Overriding, etc)

Here I try to explain different OOPs concepts in C#.NET using examples only with very less description as it is only for revision purpose (both syntax & concept).

Below I have shown my sample console program to use different OOPs concepts

*********ArunKakkarConsoleApp1************************


using System;
using System.Collections.Generic;
using System.Text;

using System.Text.RegularExpressions;

//Using Events Method 1 (a) -->>by Inheriting ArrayList
//below namespace is used form Event learning in c#.Net
namespace myListNamespace
{
    using System.Collections;

    //step 1. delegate type for hooking up change (event)  notification
    public delegate void myDelChangedEventHandler(object sender,EventArgs e);

    public class myListClass : ArrayList
    {
        //step 2. declare event that clients can be used to notified
        //--------whenever the event raised (here elements of list change)
        public event myDelChangedEventHandler myEventChanged;

        //step 3. Raise Event (here whenever elements of list changes)
        protected virtual void myEventRaisedOnChanged(EventArgs e)
        {
            if (myEventChanged != null)
                myEventChanged(this, e);      
        }

        //step 4. create such methods etc which may raise the event
        //below are methods(add,clear,this) which r override as they may change the list
        //& in each method event is invoked
        public override int Add(object value)
        {
            int i= base.Add(value);
            myEventRaisedOnChanged(EventArgs.Empty);
            return i;
        }
        public override void Clear()
        {
            base.Clear();
            myEventRaisedOnChanged(EventArgs.Empty);
        }
        public override object this[int index]
        {
            get
            {
               return base[index];
            }
            set
            {
                base[index] = value;
                myEventRaisedOnChanged(EventArgs.Empty);
            }
        }
    }
}
namespace ArunKakkarConsoleApp1
{
    //below namespace is used to learn Events in C#.Net
    using myListNamespace;

    //Different Types of Constructor
    public class InstanceConstructor
    {
        private int x, y;
        public InstanceConstructor()
        {
            x = 0;
            y = 0;
            Console.WriteLine("in Parameterless contructor,x={0}, y={1}", x, y);
        }
        public InstanceConstructor(int i)
        {
            x = i;
            y = 0;
            Console.WriteLine("In single parameter constructor, x={0}, y={1}", x, y);
        }
        public InstanceConstructor(int i, int j)
        {
            this.x = i;
            this.y = j;
            Console.WriteLine("In double parameter constructor, x={0}, y={1}", x, y);
        }
        ~InstanceConstructor()
        {
            Console.WriteLine("Destructor of class InstanceConstructor is called");
            Console.ReadLine();
        }
    }
    public class myDefaultConstructorClass
    {
        private int _x;
        private string _s;
        public int x
        {
            get
            {
                return _x;
            }
            set
            {
                _x = value;
            }      
        }
        public string s
        {
            get
            {
                return _s;
            }
            set
            {
                _s = value;
            }
        }
        public void myShow()
        {
            //if (_x==null )
            //    Console.WriteLine("X is null");
            //if(_x != null )
                Console.WriteLine("x is not null ,x={0}",_x);          
        }
    }
    public class myPrivateConstructor
    {
        public const double pi = 3.14;
        private myPrivateConstructor()
        {
        }
    }
    public class myStaticConstructorClass
    {
        //Static constructor :
        //Static Constructors are used to instantiate static data fields in the class. Static Constructors are called only once no matter how many instances you create for that class.
        //Static Constructors are executed before any other type of constructor. Static Constructors cannot be called explicitly. They are automatically invoked when
            //An instance of the class is created
            //Any of the static members of the class are referenced
        //It is a compile time error to have access modifiers for static constructors.

        public int j;
        public static int i;

        public myStaticConstructorClass()
        {
            j = 25;
            Console.WriteLine("\n Normal Instance constructor of myStaticConstructorClass is invoked");
        }
     
        static myStaticConstructorClass()
        {
            i = 20;
            Console.WriteLine("\n static constructor of myStaticConstructorClass is invoked");
        }
    }
 
    //Static Class
    public static class myStaticClass1
    {
        public static int myVal;
        //we can declare only static constructor in a static class
        //public myStaticClass1()
     
        //we can not use public etc modifire on the static class constructor
        //public static myStaticClass1()

        //not mandatory to declare constructor for a static class i.e. we can use class without any constructor
        static myStaticClass1()
        {
            myVal = 30;
        }
        public static void myShow()
        {
            Console.WriteLine("\n Hello it is myShow() method of myStaticClass1");
        }
        //we can declare only static members in a static class
        //public void myShow2()
        //{  Console.WriteLine("\nHello it is myShow2() method of myStaticClass1");        }
    }
 
    //Polymorphism & Inheritance (Virtual->Override,  Virtual->Override->Sealed, on creating instance of child class,sequence of constructor invoked 1. GrandParent 2.Parent 3.Child)
    public class myParent
    {
        private string s;
        //protected myParent()
        public myParent()
        {
            s=@"This is a string from parent class have both \ and & signs";
            Console.WriteLine("This is myParent class constructor");
        }

        public string ParseBackSlash()
        {
            string s1;
            s1=s;
            s1=s1.Replace("\\",string.Empty);
            return s1;
        }
        public virtual void ShowMsg()
        {
            Console.WriteLine("This is showmsg from myParent class");      
        }
        public virtual void myShowMsg5()
        {
            Console.WriteLine("this is myShowMsg5 method of myParent class");
        }
    }
    public class myChild1 : myParent
    {
        public string ParseAmpersand()
        {
            string s2;
            s2 = base.ParseBackSlash();
            s2 = s2.Replace("&", string.Empty);
            return s2;
        }
        public override void ShowMsg()
        {
            Console.WriteLine("This is showmsg from myChild1 class");      
        }
        public sealed override void myShowMsg5()
        {
           //base.myShowMsg5();
            Console.WriteLine("This is override sealed method myShowMsg5 which is originally of myParent class");

        }
    }
    public class myChild2 : myParent
    {
        public myChild2()
        {
            Console.WriteLine("This is myChild2 class constructor");      
        }

        public override void ShowMsg()
        {
             //base.ShowMsg();
            Console.WriteLine("this is ShowMsg method of myChild2 class");
        }

        public void myShowAns()
        {
            Console.WriteLine("This is myShowAns method of myChild2 class");
        }
    }
    public class myGrandChild1 : myChild2
    {
        public myGrandChild1()
        {
            Console.WriteLine("This is constructor of myGrandChild1 class, its parent class is myChild2, its grandParentClass is myParent");
        }  
    }
 
    //Interface handling
    public interface myInterface_1
    {
        //i/f can't contain fields
        //protected int x;
        string id
        {
            get;
            set;
        }
     
        void myShowResult();

        //if we declare this here & do not implement it & use i/f then show compile time error
        //void myWish();  
    }
    interface myInterface_2
    {
        void myShowResult();
    }
    public class myClassUsingInterface1 :myInterface_1
    {
        protected string  x;
        public string id
        {
            get
            {
                return x;
            }
            set
            {
                x = value;
            }
        }
        public myClassUsingInterface1()
        {
            Console.WriteLine("this is constructor of myClassUsingInterface1");
        }
        public void myShowResult()
        {
            Console.WriteLine("This is myshowResult of myInterface_1 implement by myClassUsingInterface1");
        }
    }
    public class myClassUsingInterface2 : myInterface_1, myInterface_2
    {
        string  x;
        public string id
        {
            get
            {
                return x;
            }
            set
            {
                x = value;
            }
        }
        public void myShowResult()
        {
            Console.WriteLine("This is myShowResult method which is common in both myInterface_1 & myInterface_2 implement by myClassUsingInterface2");
        }
    }
    //Explicitly members of interfaces
    public class myClassUsingInterface3 : myInterface_1, myInterface_2
    {
        string y;
        public string id
        {
            get
            {
                return y;
            }
            set
            {
                y = value;
            }      
        }

        //Explicitly members of interfaces>>>> we can't use public etc keywords
        void myInterface_1.myShowResult()
        {
            Console.WriteLine("This is myInterface_1.myShowResult() method called");
        }
        void myInterface_2.myShowResult()
        {
            Console.WriteLine("This is myInterface_2.myShowResult() method called");
        }  
    }
 
    //Abstract Class
    public abstract class myAbstractClass
    {
        public void myShowMessage()
        {
            Console.WriteLine("my showmsg method of myAbstractClass class");      
        }
        public abstract  void myShowMessage2();
    }
    public class myChild3 : myAbstractClass
    {
        public void myShowMessage3()
        {
            base.myShowMessage();
            Console.WriteLine("This is myShowMessage3 method of myChild3 class");
        }
        public override void myShowMessage2()
        {
            //base.myShowMessage2();
            Console.WriteLine("This is from myShowMessage2 override by myChild3 class");
        }  
    }
 
    //Sealed Classes
    public sealed class myChild4 : myChild3
    {
        public int myAddNumbers(int x, int y)
        {
            return x + y;
        }
        public void myShowMsg4()
        {
            Console.WriteLine("this is myShowMsg4 from sealed class myChild4");      
        }

        public void myShowMsg5(int i)
        {
            Console.WriteLine("myShowMsg5 called with i=" + i);
        }
        public void myShowMsg6(int j)
        {
            Console.WriteLine("myShowMsg6 called with j={0}", j);
        }    
    }

    //5. Delegates  & events
    //(publisher [who declare/create event & told all subscriber that a particular event is raised]
    //& subsriber(who write code for event handler))

    //Using Events Method 1 (b) -->>by Inheriting ArrayList
    public class myEventListner
    {
        //step 5. class that listen the events raised by event class
        private myListClass myList;

        //step 6. create method that acts as event handler
        //called whenever list changes
        private void myListChanged(object sender, EventArgs e)
        {
            Console.WriteLine("myListChanged method is called when event(change in list) fired");
        }
        public myEventListner(myListClass myL1)
        {
            myList = myL1;
            //step 7. add events
            myList.myEventChanged += new myDelChangedEventHandler(myListChanged);
        }
        public void myDetach()
        {
            //step 8. Detach the event & delete the list
            myList.myEventChanged -= new myDelChangedEventHandler(myListChanged);
            myList = null;
        }
    }

    //Using Events Method 2 -->> Events as Publisher & Subscriber
    public class myPublisher      
    {
        //using System.Windows.Forms
        public delegate void myDelegate2(object from, EventArgs args);
        public event  myDelegate2  myEvent;
        public void myRaiseMyEvent(EventArgs args)
        {
            myEvent(this, args);
        }

        public void SendTheEvent()
        {
            Console.WriteLine("The event is fired here in SendTheEvent method of publisher class");
            this.myRaiseMyEvent(new EventArgs());      
        }
    }
    public class mySubscriber
    {
        private void myHandleMyEvent(object sender, EventArgs args)
        {
            Console.WriteLine("myEvent is handled in the myHandleMyEvent of the mySubscriber class");
            Console.WriteLine("who is the sender ? " + sender.GetType());
        }
        public mySubscriber()
        {
            myPublisher p1 = new myPublisher();
            p1.myEvent += new myPublisher.myDelegate2(myHandleMyEvent);
            p1.SendTheEvent();
        }
    }

    //Using Events Method 3 --->> Event using built-in event delegate "EventHandler"
    public class myEventPublisherWithDefaultDelegate
    {
        //For events that do not use any additional information, the .NET Framework has already defined an
            //appropriate delegate type: EventHandler.

        //If we not use EventHandler keyword, we need to define a Delegate(say myEvent2Delegate) eqvivalent to EventHanler
        private string _myVal;
        public event EventHandler myEvent2;
        public void myEvent2Raiser(EventArgs e)
        {
            myEvent2(this, e);
        }
        public string myVal
        {
            get
            {
                return _myVal;
            }
            set
            {
                _myVal = value;
                this.myEvent2Raiser(new EventArgs());
            }
        }
    }
    public class myEventSubscriberWithDefaultDelegate
    {
        public void myEvent2Handler(object sender, EventArgs e)
        {
            Console.WriteLine("\nThis is myEvent2Handler called since Event myEvent2 is raised");
            Console.WriteLine("\n It is called by = " + this.GetType());
        }
        public myEventSubscriberWithDefaultDelegate()
        {
            myEventPublisherWithDefaultDelegate p1 = new myEventPublisherWithDefaultDelegate();
            p1.myEvent2 +=new EventHandler(this.myEvent2Handler);
            p1.myVal ="ram Ram";
            p1.myVal +=" Hare Ram";
        }
    }

    class Program
    {
        //Delegate Handling ( Single Cast,  MultiCast )
        public delegate int myDel(int a, int b);
        public delegate void myDel2();
        public delegate void myMultiCastDel(int m);

        static void Main(string[] args)
        {            
            //------------------------ Topics ---------------------------------------------------------------
            //OOPS CONCEPTS
            //1. Types of Constructor (a. Default, b. Instance, c. Private, d. Static) & Destructor
            //2. Types of Classes 
                //a. Static, 
                //b. Abstract {(abstract & override) & abstract methods}, 
                //c. Sealed  (can not be inherited) & sealed override methods
                //complete syntax of a class with all options explained
            //3. Inheritance (Virtual & override), properties, static variables, private,protected,public variables etc
            //4. Polymorphism, Early/Static/CompileTime Binding & Late/Dynamic/Runtime Binding
            //5. Interface & Explicitly declaration
            //6. Delegate (Signle Cast & MultiCast)
            //7. Events
            //-------------------------------            
            //8. Regular Expression
            //9. Number To Words
            //10.Webservice
            //-------------------------------------------------------------------------------------

            //1(a). Type of Constructors-->Instance Constructor
            InstanceConstructor ic1 = new InstanceConstructor();
            InstanceConstructor ic2 = new InstanceConstructor(3);
            InstanceConstructor ic3 = new InstanceConstructor(4,5);

                //Destructor
            ic1 = null;
            GC.Collect(); //Call Garbage collector

            //1(b). Type of Constructors-->Default Constructor
            myDefaultConstructorClass dc1 = new myDefaultConstructorClass();
            Console.WriteLine(" before giving values, x={0},s={0}", dc1.x, dc1.s);
            dc1.myShow();
            dc1.x = 25;
            dc1.s = "Arun Kakkar";
            Console.WriteLine("After giving values, x={0},s={1}", dc1.x, dc1.s);
            dc1.myShow();

            //1(c). Type of Constructors-->Private constructor
            Console.WriteLine("private class value, x=" + myPrivateConstructor.pi);
            Console.ReadLine();

            //1(d). Type of Constructors-->Static Constructor
            Console.WriteLine("mystaticConstructorClass class value, x={0}", myStaticConstructorClass.i);
            Console.ReadLine();

            myStaticConstructorClass scs1=new myStaticConstructorClass();
            Console.WriteLine("\n j={0} and i={1} in myStaticConstructorClass ",scs1.j ,myStaticConstructorClass.i);
            Console.ReadLine();

            //2(a). Types of Classes---> Static Class            
            myStaticClass1.myShow();
            Console.WriteLine("\n MyVal of myStaticClass1 is=" + myStaticClass1.myVal);
            myStaticClass1.myVal = 23;
            Console.WriteLine("\n MyVal after updation of myStaticClass1 is=" + myStaticClass1.myVal);

            //2(b). Types of Classes---> Abstract class 
            myChild3 ch3 = new myChild3();
                //string s1 = "below";
                //s1 = "ch3.myShowMessage=" + ch3.myShowMessage() + "\n";
                //s1 += "ch3.myShowMessage2=" + ch3.myShowMessage2() + "\n";
                //s1 += "ch3.myShowMessage3=" + ch3.myShowMessage3();
            Console.WriteLine("various functions called by myChild3 class of parent abstract class are as below \n");
            ch3.myShowMessage();
            ch3.myShowMessage2();
            ch3.myShowMessage3();

            //2(c). Types of Classes---> Sealed classes 
                //(can not be inherited)
                //A sealed class can not be used as "base class"
                //A sealed class can not be an abstract class.
                //sealing a class means one(class) can not be driven(drived) from it
                // In C# structs are implicitly sealed.
                //In C# methods can't be declared as sealed but when we override a method(in derived class), 
                //we can declared the overriden method as sealed thus we cannot override this method further

                //public virtual void m1();  in any parent class
                //public override sealed void m1() in the child class

            myChild4 ch4 = new myChild4();
            ch4.myShowMsg4();

            //override Sealed method
            myChild1 ch1 = new myChild1();
            ch1.myShowMsg5();

            //3. Inheritance (Virtual & override), properties, static variables, private,protected,public variables etc ***************
                //1. when we create child class instance, then first parent class constructor is called then child class constructor is called
                //    & they (Constructors) are called in order from top to down sequentially.
                //2. "this" keyword show all methods,etc of both current class & all its parent class >>>this.myShowMsg()
                // but "base" keyowrd show methods of only parent class >>>base.myShowMsg()
                //3. if u don't give any modifiers to constructor,variables they are "private" by default
                //4. if both current class & parent class have same name funtion without using "virtual" keyword in the parent, we get compile time error
            myChild1 c1 = new myChild1();
            c1.ShowMsg();
            Console.WriteLine("the parsed string is=" + c1.ParseAmpersand());
            
            myChild2 c2 = new myChild2();
            c2.myShowAns();

            myGrandChild1 mgc1 = new myGrandChild1();
            mgc1.myShowAns();
            mgc1.ShowMsg();

            //4. Polymorphism, Early/Static/CompileTime Binding & Late/Dynamic/Runtime Binding
                //Polymorphism=>Through inheritance, a class can be used as more than one type;
                // it can be used as its own type, any base type, or any interface type if it 
                //implements interface. This is called Polymorphism.
            myParent myP1 = new myParent();
            myChild1 myCh1 = new myChild1();
            myChild2 myCh2 = new myChild2();

                //Early/Static/CompileTime binding
            Console.WriteLine("\n Below are Early Binding ShowMsg calls from myparent,child1,child2 classes");
            myP1.ShowMsg();
            myCh1.ShowMsg();
            myCh2.ShowMsg();
             
            //Late/Dynamic/Runtime binding
            myParent[] myP2 = new myParent[3];
            myP2[0] = new myParent();
            myP2[1] = new myChild1();
            myP2[2] = new myChild2();

            Console.WriteLine("\n Below are Late Binding ShowMsg calls from myparent,child1,child2 classes");
            for (int i = 0; i <= 2; i++)
            {
                myP2[i].ShowMsg();
            }
                    //below can be used instead of above loop
                    //myP2[0].ShowMsg();
                    //myP2[1].ShowMsg();
                    //myP2[2].ShowMsg();

            //5. Interface & Explicitly declaration
                //1. all methods of i/f must be implement by class implement i/f else get compile time error
                //2. inside i/f>>  void myShowMsg(); is enough i.e. no need to be public etc
            myClassUsingInterface1 cui1 = new myClassUsingInterface1();
            cui1.myShowResult();
            cui1.id = "ram ram";
            Console.WriteLine("Value of cui1.id=" + cui1.id);

            myClassUsingInterface2 cui2 = new myClassUsingInterface2();
            cui2.myShowResult();

                //Explicitly members of interfaces
            myClassUsingInterface3 myif3 = new myClassUsingInterface3();
            myif3.id = "ram ram ji from myIf3";
            Console.WriteLine("calling myif3.id=" + myif3.id);

            myInterface_1 myinterface1 = (myInterface_1)myif3;
            myInterface_2 myinterface2 = (myInterface_2)myif3;

            myinterface1.myShowResult();
            myinterface2.myShowResult();
            Console.WriteLine("calling myinterface1.id={0}", myinterface1.id);

            //6. Delegate (Signle Cast & MultiCast)
                //delegate are derived from System.Delegate
                //below line declared above the void main method
                //public delegate int myDel(int a, int b);
            myDel d1=new myDel(ch4.myAddNumbers);
            Console.WriteLine("addition of 20 & 30 using delegates is=" + d1(20, 30));

                //SingleCast delegate
            myDel2 d2 = new myDel2(ch4.myShowMessage);
            Console.WriteLine("void method using delegate is=\n");
            d2();

                //MultiCast Delegate
                //call more than one kind of method in sequence but problem is only same value of parameter is passed in all methods
            Console.WriteLine("Below line show multicast delegate result\n");
            myMultiCastDel d3 = new myMultiCastDel(ch4.myShowMsg5);
            d3 += new myMultiCastDel(ch4.myShowMsg6);
            d3(3);

            //7(a). Events  --->Method 1
                //Event handling using UserDefined EventDelegate
            Console.WriteLine("\nBelow line show delegate and events combination result");
            mySubscriber sub1 = new mySubscriber();

            //7(b). Events  --->Method 2
                //Event Handling using Default (DotNet framework provided EventDelegate named 'EventHandler')
            Console.WriteLine("\nBelow line shows event handling with default in-built EventDelegate named 'EventHandler'");
            myEventSubscriberWithDefaultDelegate mySub1 = new myEventSubscriberWithDefaultDelegate();

            //7(c). Events  --->Method 3
                //create new list to test Events in C#.Net
            myListClass myL = new myListClass();
                //create class that listen event (whenver list item changed) of list 
            myEventListner myE = new myEventListner(myL);
                //Add & remove items from the list
            Console.WriteLine("\nThis line before any event is fired in list class");
            myL.Add("item 1");
            Console.WriteLine("\nThis line after adding item 1 in list class");
            myL.Add("item 2");
            Console.WriteLine("\nThis line after adding item 2 in list class");
            myL.Clear();
            Console.WriteLine("This line after clearing all items in list class");
            myE.myDetach();
            Console.WriteLine("This line after detaching event from the myEventLister class");

            //8. Regular Expression
            Console.WriteLine("Please enter any alphanumeric word only it can include underscore(_) also=");
            string s = Console.ReadLine();
            string r = @"^[\w]+$";
            if (Regex.IsMatch(s, r))
            {
                Console.WriteLine("You have entered an alphanumeric word=" + s);
            }
            else
            {
                Console.WriteLine("Its a wrong word please enter only Alphanumeric word");
            }
            Console.ReadLine();   // just like getch() in C++
         
            //10.Webservice calling --Webservice1    
            localhostAK.ArunKakkarwsCustomers myWS = new localhostAK.ArunKakkarwsCustomers();
            Console.WriteLine("customer name from WebService localhostAK.ArunKakkarwsCustomers is {0}", myWS.GetCustomerName(2));

                //webservice 2
            AKWebService_1.ArunKakkarWebServices akws1 = new AKWebService_1.ArunKakkarWebServices();
            Console.WriteLine("Addition of {0} and {1} from WebService AKWebService_1.ArunKakkarWebServices is {2}",5,9, akws1.Add2IntNo(5,9));

            //globalweather_NetWS   webservice 3 download from net with link http://www.webservicex.com/globalweather.asmx?WSDL
            string myCountry;
            GlobalWeather_NetWS.GlobalWeather gw = new GlobalWeather_NetWS.GlobalWeather();
            Console.WriteLine("\nEnter country name to get list of its all cities");
            myCountry = Console.ReadLine();
            //it return a dataset in xml format
            Console.WriteLine("\n Various cities in {0} are {1}", myCountry, gw.GetCitiesByCountry(myCountry));


            Console.ReadLine();
        }
    }
}




I hope, it would help those who want to just quickly revise OOPs concepts (both syntax & use).
Due to lack of time, I did not provide, description of various terms.

Wish you best of luck for good programming.