Sunday, January 20, 2013

Difference between Jagged Array and Multi Dimension Array in C#?


Jagged Array

A jagged array is an array whose element is arrays and the element of jagged array could be of different size and dimension.

Multi Dimension Array

A multi dimension array is an array whose element will be of same size.


Jagged Array Example


       
     
         
   

3-Dimension Array Example


     
     
     


Example

    class JaggedArray
    {
        static void Main()
        {
            // Declare jagged array of size 4.
            int[][] objJaggedArray = new int[4][];

            // Initialization jagged array.
            objJaggedArray[0] = new int[4];
            objJaggedArray[1] = new int[3];
            objJaggedArray[2] = new int[5];
            objJaggedArray[3] = new int[2];


            objJaggedArray[0] = new int[] { 9, 8, 7, 6 };
            objJaggedArray[1] = new int[] { 9, 8, 7 };
            objJaggedArray[2] = new int[] { 9, 8, 7, 6, 5 };
            objJaggedArray[3] = new int[] { 9, 8 };

            Console.WriteLine("Jagged Array Items...");

           // Display the jagged array elements:              
            for (int i = 0; i < objJaggedArray.Length; i++)
            {
                Console.WriteLine();
                for (int j = 0; j < objJaggedArray[i].Length; j++)
                {
                    Console.Write(objJaggedArray[i][j]+ " ");
                }
            }

            Console.WriteLine();

            int[,] myArray = new int[3, 3];
            myArray[0, 0] = 1;
            myArray[0, 1] = 2;
            myArray[0, 2] = 3;
            myArray[1, 0] = 4;
            myArray[1, 1] = 5;
            myArray[1, 2] = 6;
            myArray[2, 0] = 7;
            myArray[2, 1] = 8;
            myArray[2, 2] = 9;

            Console.WriteLine("3D Array Items...");

            // Display the 2D array elements:             
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    Console.Write(myArray[i, j] + " ");
                }
                Console.WriteLine();
            }            


            Console.ReadLine(); 

        }
    }
            

Output

Jagged Array Items...
9 8 7 6
9 8 7
9 8 7 6 5
9 8

3D Array Items...
1 2 3
4 5 6
7 8 9

What is the top .NET class that everything is derived from?


Top .NET class

Every class in .NET inherit from System.Object class. To make sure, just create a blank class and create an object of this class. System.Object class contains four default methods and these method can be accessed by any of the class object. It prove that all the classes are inherit from System.Object class.

Methods of System.Object Class:


  • Equals
  • GetHashCode
  • GetType
  • ToSting


Example

    class abc          
    {
        public string MyMethod()
        {
            return "Welcome";
        }
    }  

     class Program
     {
        static void Main(string[] args)
         {
            abc obj = new abc();
            Console.WriteLine("abc class method MyMethod() - " + obj.MyMethod());
            Console.WriteLine("System.Object class method GetHashCode()- " + obj.GetHashCode());
            Console.WriteLine("System.Object class method GetType()- " + obj.GetType());
            Console.WriteLine("System.Object class method ToString()- " + obj.ToString());
            Console.ReadLine();
         }
     }

Output

abc class method MyMethod() – Welcome
System.Object class method GetHashCode()- 45653674
System.Object class method GetType()- ConsoleApplication1.abc
System.Object class method ToString()-ConsoleApplication1.abc

Note.The above code is showing that the abc class contain only one method but we are accessing more methods like GetHashCode, GetType etc. so these methods are coming from base class which is System.Object

Can you declare an override method as static if the original method is not static?


No, you can not do that. There are two reason for that.


  • Signature of the method in base class and derive class should be the same. 
  • A static member cannot be marked as override, virtual or abstract.

Multiple interfaces conflicting method names?


Multiple interfaces conflicting method names

Nothing happens, application will get compiled and execute properly. There are two ways to implement interface with conflict method name.

Example

          public interface MyInterface1
          {
             int Add(int i, int j)
          }

          public interface MyInterface2
          {
             int Add(int i, int j)
          }  

Solution 1.

          public class MyClass : MyInterface1, MyInterface2                
          {
             public int Add(int i, int j)
             {
                 return i + j;
             }
          }

Solution 2.

        public class MyClass : MyInterface1, MyInterface2
        {
            public int Add(int i, int j)
            {
                return i + j;
            }

            int MyInterface2.Add(int i, int j)
            {
                return i + j + 5;
            }
       }

        static void Main(string[] args)
        {
            MyInterface1 obj1 = new MyClass();
            int i = obj1.Add(1, 2);
            Console.WriteLine(i);

            MyInterface2 obj2 = new MyClass();
            int j = obj2.Add(1, 2);
            Console.WriteLine(j);
        }
       

Output 

    3
    8

Call base class parameterize constructor from derive class constructor in c#?


Call base class parameterize constructor 

Base class constructor automatically call if it is not parameterize. You don’t need to write down extra code for that. But if base class construcotor is parameterize then you have to write down some code to call the base class constructor.

Syntex:

Add the below code next to the derive class constructor.

: base(parameter)

Example

   // Base Class.  
    public class Parent
    {
        string _empName = string.Empty;

        //Base class constructor.  
        public Parent(string name)
        {
            _empName = name;
        }

        public string EmpName
        {
            get
            {
                return _empName;
            }
        }
    }

    // derive Class.
    public class Child : Parent
    {
        int _empAge;

        // derive class constructor
        public Child(string name, int age)
            : base(name) //  Calling base class constructor with parameter.
        {
            _empAge = age;
        }

        public int EmpAge
        {
            get
            {
                return _empAge;
            }
        }
    }


    static void Main(string[] args)
    {
        Child objChild = new Child("Anil", 25);
        Console.WriteLine("Name - "+objChild.EmpName);
        Console.WriteLine("Age - " + objChild.EmpAge);
    }

Output

Name – Anil
Age - 25

Note: In base class and derive class, every time base class constructor first call and then derive class constructor call.

What is Jagged Array in C#?


Jagged Array

An array of arrays is called Jagged Array i.e. a jagged array is an array whose element is arrays. The element of jagged arraycan be of different size and dimension.

Jagged Array Example

    class JaggedArray
    {
        static void Main()
        {
            // Declare jagged array of size 4.
            int[][] objJaggedArray = new int[4][];

            // Initialization jagged array.
            objJaggedArray[0] = new int[4];
            objJaggedArray[1] = new int[3];
            objJaggedArray[2] = new int[5];
            objJaggedArray[3] = new int[2];


            objJaggedArray[0] = new int[] { 9, 8, 7, 6 };
            objJaggedArray[1] = new int[] { 9, 8, 7 };
            objJaggedArray[2] = new int[] { 9, 8, 7, 6, 5 };
            objJaggedArray[3] = new int[] { 9, 8 };

            Console.WriteLine("Jagged Array Items...");

            // Display the jagged array elements:            
            for (int i = 0; i < objJaggedArray.Length; i++)
            {
                Console.WriteLine();
                for (int j = 0; j < objJaggedArray[i].Length; j++)
                {
                    Console.Write(objJaggedArray[i][j]+ " ");
                }
            }
            Console.ReadLine();

        }
   }

Output

Jagged Array Items...
9 8 7 6
9 8 7
9 8 7 6 5
9 8

Difference between BeginInvoke and Invoke in Delegates?


Delegate.Invoke

Delegate.Invoke works on the same thread. It is used to execute a delegate on the same thread. No other thread is used to execute a delegate.

Delegate.BeginInvoke

Delegate.BeginInvoke works on a separate thread, not on the same thread. It is used to execute a delegate asynchronously. BeginInvoke doesn’t block your current thread, it execute separately so it execute in the background.

Note: If you use BeginInvoke, you have to use EndInvoke to get the result.

Example

    public class MulticastDelegate
    {
        delegate string MyDelegate(string message);

        static void Main()
        {
            MyDelegate objMyDelegate1 = new MyDelegate(WriteLog);
            MyDelegate objMyDelegate2 = new MyDelegate(SendEmail);

            AsyncCallback objcallback = new AsyncCallback(DisplayResult);
            Console.WriteLine("Start..");

            objMyDelegate1.BeginInvoke("Operation failed..", objcallback, null);
            objMyDelegate2.BeginInvoke("Operation failed..", objcallback, null);

            Console.WriteLine("Main thread continuing..");

            Thread.Sleep(3000);
            Console.WriteLine("Done..");

            Console.ReadLine();
        }

        static void DisplayResult(IAsyncResult result)
        {
            string format = (string)result.AsyncState;
            AsyncResult delegateResult = (AsyncResult)result;
            MyDelegate delegateInstance = (MyDelegate)delegateResult.AsyncDelegate;

            Console.WriteLine(delegateInstance.EndInvoke(result));
        }

        static string WriteLog(string message)
        {
            Thread.Sleep(2000);
            Console.WriteLine("WriteLog :- " + message);

            return "WriteLog Done!";
        }

        static string SendEmail(string message)
        {
            Thread.Sleep(1000);
            Console.WriteLine("SendEmail :- " + message);

            return "SendEmail Done!";
        }
     }
}

Output

Start..
Main thread continuing..
SendEmail :- Operation failed..
SendEmail Done!
WriteLog :- Operation failed..
WriteLog Done!
Done..

How to retrieve values from multicast delegate in C#?


Retrieve values from multicast delegate

We use multicast delegate to have multiple methods and by single invoke, all the reference methods get called. This is a good practice for the functions those having return type 'void'. But if your functions return some value then there is a different way to get the return value.


Get last method return value

    public class Class1
    {
        public int Method1()
        {
            return 1;
        }
    }

    public class Class2
    {
        public int Method2()
        {
            return 2;
        }
    }

    public class Class3
    {
        public int Method3()
        {
            return 3;
        }
    }  


    public class Operatinos
    {
        public delegate int MyDelegate();
        MyDelegate objMyDelegate;

        Class1 objClass1 = null;
        Class2 objClass2 = null;
        Class3 objClass3 = null;

        //Constructor
        public Operatinos()
        {
            objClass1 = new Class1();
            objClass2 = new Class2();
            objClass3 = new Class3();


            objMyDelegate += objClass1.Method1;
            objMyDelegate += objClass2.Method2;
            objMyDelegate += objClass3.Method3;
        }

        public void OperationFailed()
        {
            int i = objMyDelegate.Invoke();
            Console.WriteLine(“Return value :- “ + i.ToString());

        }
    }

    public class MulticastDelegateReturnValue
    {
        static void Main()
        {
            Operatinos op = new Operatinos();
            op.OperationFailed();

            Console.ReadLine();
        }
    }

Output

Return value :- 3


Get all method return value

Use above sample and only modify the operation class to get the all function return value.

    public class Operatinos
    {
        public delegate int MyDelegate();
        MyDelegate objMyDelegate;

        Class1 objClass1 = null;
        Class2 objClass2 = null;
        Class3 objClass3 = null;

        //Constructor
        public Operatinos()
        {
            objClass1 = new Class1();
            objClass2 = new Class2();
            objClass3 = new Class3();


            objMyDelegate += objClass1.Method1;
            objMyDelegate += objClass2.Method2;
            objMyDelegate += objClass3.Method3;
        }

        public void OperationFailed()
        {
            foreach (MyDelegate del in objMyDelegate.GetInvocationList())
            {
                int i = del();

                Console.WriteLine("Return value :-" + i.ToString());
            }
        }
    }
            

Output

Return value :- 1
Return value :- 2
Return value :- 3

Virtual keyword declaration for a method or property?

Virtual keyword

Virtual” keyword is used in a base class with method or property to override in derive class i.e. the “Virtual” method or property can be overridden in derive class. 

Virtual Example

    // Base class 
    class Parent
    {
        public virtual int Calculation(int i, int j)
        {
            return i * j;
        }

    }

    // Derive class
    class child : Parent
    {
        public override int Calculation(int i, int j)
        {
            return i / j;
        }
    }

        static void Main(string[] args)
        {
            Parent obj = new Parent();
            int i = obj.Calculation(20, 10);
            Console.WriteLine(i);

            Parent obj1 = new child();
            int j = obj1.Calculation(20, 10);
            Console.WriteLine(j);
        }

Output

200
2

Saturday, January 19, 2013

What is Anonymous Methods in c#?


Anonymous Methods

Anonymous Methods allows you to define the code block where you create an object of the delegate. We don’t need to create a separate method for the delegate. Anonymous Methods are useful only for small code because Anonymous Methods code is not reusable, no one can directly call it.

Example: With Anonymous Methods


    class MyDelegates
    {
        // Declare a delegate
        delegate void DisplayMessage(string str);

        static void Main(string[] args)
        {
            //DisplayMessage delegate instance create with Anonymous Method.
            DisplayMessage del = delegate(string str)
            {
                Console.WriteLine(str);
            };

            del("Welcome..");          
            Console.ReadLine();
        }
    }

   Output 

    Welcome..


Example: Without Anonymous Methods


    class MyDelegates
    {
        // Declare a delegate
        delegate void DisplayMessage(string str);

        static void Main(string[] args)
        {
            //Create DisplayMessage delegate instance with Message Method.
            DisplayMessage del = new DisplayMessage(Message);
            del.Invoke("Welcome..");
            Console.ReadLine();
        }

        static void Message(string str)
        {
            Console.WriteLine(str);
        }
    }
   

   Output 

   Welcome..

Can we serialize Hashtable and Dictionary in C#


Hashtable and Dictionary

No, we can not serialized Hashtable and Dictionary. There are two reason for that.


  • Hashtable and Dictionary both are implemented from IDictionay interface. We need XML serializer to serialize the Hashtable and Dictionary. XML serializer doesn't support IDictionay interface.

  • Hashtable and Dictionary both are implemented from IEnumerable interface. IEnumerable works with yield keyword. Basically compiler generate a separate class to implement yield functionality and generated class is not seriazible i.e. generated class is not marked as serializable.

Does C# support multiple inheritances


No, C# does not support multiple inheritance. Through interface, you can achieve multiple inheritance.

Example

        public interface MyInterface1
        {
            int Add(int i, int j);
        }

        public interface MyInterface2
        {
            int Sub(int i, int j);
        }

        public class Math : MyInterface1, MyInterface2
        {
            public int Add(int i, int j)
            {
                return i + j;
            }

            public int Sub(int i, int j)
            {
                return i - j;
            }
        }

    class Program
    {
        static void Main(string[] args)
        {
            Math obj = new Math();

            int i = obj.Add(20, 10);
            Console.WriteLine(i);

            int j = obj.Sub(20, 10);
            Console.WriteLine(j);

        }
   }

Difference between Process and Thread



To understand process and thread, lets take a example of MSWord.

When you click on MSWord icon, a MSWord file open. This is the process . When MSWord file open, you can do multiple operation at same time. Ex – print command, typing on the file etc. This is the thread .

Process

Process is a programm which we execute. We use process for a heavy weight task because a process can have multiple threads.

Thread

Thread is nothing, it is the part of process. A process run at least one thread (main thread). A process can have multiple threads. A thread is generally used for light weight talk.

Sunday, January 13, 2013

Difference between function overloading and function overriding in C#?


Function overloading

Function overloading means more than one function with same name and different signature. i.e. function name same and parameter are different. These function can be exist in the same class or in the base and derive class.

Method overloading is the example of compile time polymorphism

Example

class FunctionOverloading
{
    //function GetName with one parameter.
    public string GetName(string name)
    {
        return "My name is :- " + name;
    }

    //function GetName with two parameter.
    public string GetName(string firstName, string lastName)
    {
        return "My name is :- " + firstName + " " + lastName;
    }

     //function GetName with three parameter.
    public string GetName(string firstName, string lastName, string surname)
    {
        return "My name is :- " + firstName + " " + lastName + " " + surname;
    }
}

class Program
{
    static void Main(string[] args)
    {
        FunctionOverloading obj = new FunctionOverloading();
        string name = obj.GetName("Ram");
        Console.WriteLine(name);

        name = obj.GetName("Ram", "Kumar");
        Console.WriteLine(name);

        name = obj.GetName("Ram", "Kumar", "Verma");
        Console.WriteLine(name);
     }
}

Output

My name is :- Ram
My name is :- Ram Kumar
My name is :- Ram Kumar Verma


Function overriding

Function overriding means two function with the same name and same signature, one method in base class and another one in derive class.

We have to use virtual and override keywords with the function. Virtual keyword in the base class and override in the derive class.

Function overriding is the example of run time polymorphism.is the example of run time polymorphism. 

Example

    // Base class
    class Parent
    {
        public virtual int Calculation(int i, int j)
        {
            return i * j;
        }

    }

    // Derive class
    class child : Parent
    {
        public override int Calculation(int i, int j)
        {
            return i / j;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Parent obj = new Parent();
            int i = obj.Calculation(20, 10);
            Console.WriteLine(i);

            Parent obj1 = new child();
            int j = obj1.Calculation(20, 10);
            Console.WriteLine(j);

        }
    }

Output

200
2

Difference between Struct and Class in C#?


Struct 


  • Struct is value type so it store into stack. 
  • Struct can not be inherit.
  • No need new keyword to create an instance of a struct. New keyrowd is used only to call the constructor.


Class 


  • Class is reference type so it store into heap. 
  • Class can be inherit.
  • New keyword must use to create an instance of a class

Saturday, January 12, 2013

What is a multicast delegate in C#?



Multicast delegate

A delegate which holds the reference of multiple methods is called multicast delegate . And simple delegates hold the reference of only single method. When you invoke the multicast delegate, all the reference methods are called.

Example

    public class LogFileNotification
    {
        public void WriteLog(string message)
        {
            //Write Log into a file
            Console.WriteLine("WriteLog :- " + message);
        }
    }

    public class EmailNotification
    {
        public void SendEmail(string message)
        {
            // Send email to appropriate person.
            Console.WriteLine("EmailNotification :- " + message);
        }
    }

    public class Operatinos
    {
        public delegate void Notification(string str);
        Notification SendNotification;

        LogFileNotification logFileNotification = null;
        EmailNotification emailNotification = null;

        //Constructor
        public Operatinos()
        {
            logFileNotification = new LogFileNotification();
            emailNotification = new EmailNotification();

            SendNotification += logFileNotification.WriteLog;
            SendNotification += emailNotification.SendEmail;
        }

        public void OperationFailed()
        {
            SendNotification.Invoke("Operation is failed.");
        }
    }

    public class MulticastDelegate
    {
        static void Main()
        {
            Operatinos op = new Operatinos();
            op.OperationFailed();

            Console.ReadLine();
        }
    }
       

Output

WriteLog :- Operation is failed.
EmailNotification :- Operation is failed.

What is Copy Constructor in C#?


Copy constructor

Copy constructor is one type of constructor. It creates an object by coping value from another object.

C# does not provide a copy constructor. If you want to create an object of a class and want to copy value from the existing object, you have to write the appropriate method for that.

Example

The Employee class contains a constructor which takes Employee class object as a parameter and assign the value from the parameter object into another new object.
     
    public class Employee
    {
        private string _name;
        private int _sal;

        // Copy constructor.
        public Employee(Employee employeeObj)
        {
            _name = employeeObj._name;
            _sal = employeeObj._sal;
        }

        // Instance constructor.
        public Employee(string name, int sal)
        {
            this._name = name;
            this._sal = sal;
        }

        public string Name
        {
            get
            {
                return _name;
            }
        }
    }

    public class DisplayEmployee
    {
        static void Main()
        {
            // a new Employee class object Create.
            Employee employee1 = new Employee("Shweta", 4000);

            // Create one more new object and copying employee1 value.
            Employee employee2 = new Employee(employee1);

            Console.WriteLine(employee2.Name);          
        }
    }

Output

Shweta


Public, Private, Static, Parameterize and Copy Constructor in C#?


Private Constructor- 

Private Constructor is used to restrict the user to create an object outside the class i.e. No one can create the object of the class which contains private constructor. It is mostly used to make a Singleton class. 

Example

public class LoanData
{
    //Private Constructor 
    private LoanData()
    {
    }

    public static LoanData GetLoanData
    {
        get
        {
            object objData = HttpContext.Current.Session["LoanData"];
            if (objData == null || !(objData is LoanData))
            {
                //singleton object of LoanData 
                objData = new LoanData();
                HttpContext.Current.Session["LoanData"] = objData;
            }

            LoanData loanData = objData as LoanData;
            return loanData;
        }
    }
}

Public Constructor-

A Public constructor is a constructor which is called when a new object of a class is created. It is generally used to initialize the data. 

Characteristic 


  • Constructor does not have return type. 
  • Constructor can be parameterized.
  • Always Constructor name will be the same class name.
  • Constructor can be private and shared. 


Example

public class Employee
{
    //Public constructor.
    public Employee()
    {
    }
}

public class DisplayEmployee
{
    static void Main()
    {
        //Create a new Employee class object.
        Employee employee1 = new Employee();
    }
}

Static Constructor -

A static constructor is automatically called when first instance of the class is created. For second or more instances, it is not called. Access modifiers are not allowed on static constructor. A static constructor can not be called directly A static constructor initialized only static fields, it doesn't initialize non-static fields.

Example

public class Employee
{
    private string _name;
    private string _sal;
    static string _department;

    //Static constructor.
    static Employee()
    {
        _department = "Software";
    }
}

Copy constructor - 

Copy constructor is one type of constructor. It creates an object by coping value from another object. 
C# does not provide a copy constructor. If you want to create an object of a class and want to copy value from the existing object, you have to write the appropriate method for that.

Example

The Employee class contains a constructor which takes Employee class object as a parameter and assign the value from the parameter object into another new object.
     
public class Employee
{
    // Copy constructor.
    public Employee(Employee employeeObj)
    {
        _name = employeeObj._name;
        _sal = employeeObj._sal;
    }
}
   

Parameterize constructor - 

A Parameterize constructor is a constructor which contains one or more parameter. It is generally used when user needs to pass the value at the time of object creation.

Example

public class Employee
{
    private string _name;
    private string _sal;

    // constructor.
    public Employee()
    {
    }

    // Parameterize constructor.
    public Employee(string name, int sal)
    {
        this._name = name;
        this._sal = sal;
    }
}

public class DisplayEmployee
{
    static void Main()
    {
        //Create a new Employee class object.
        //Passing data at the time of object creation.
        Employee employee1 = new Employee("Anjali", 4000);
    }
}

Different access modifiers for get/set property?


Is it possible to have different access modifiers for get/set property? 

Yes, we can have different access modifier for get/set property.


  • You Cannot specify accessibility modifiers for both accessors (Get and Set) of the property i.e. you can specify accessibility modifiers for either Get or Set, Not for both. Otherwise you will get compilation error.
  • The accessibility modifier of the Get or Set accessor must be more restrictive than the property i.e. 
    • If property access modifier is public then you can specify Get or Set accessor as Protected, Internal, Private.
    • If property access modifier is Internal then you can specify Get or Set accessor as Private only.

Example

    public class Employee
    {
        string _name = string.Empty;
        int _sal;

         // Parameterize constructor.
        public Employee(string name, int sal)
        {
            Name = name;
            Salary = sal;
        }

        public int Salary
        {
            get
            {
                return _sal;
            }

            private set
            {
                _sal = value;
            }
        }

        public string Name
        {
            get
            {
                return _name;
            }

            private set
            {
                _name = value;
            }
        }

    }
   
    class MyClass
    {
        static void Main()
        {
            Employee obj = new Employee("Ram", 1000);
            Console.WriteLine("Name = " + obj.Name);
            Console.WriteLine("Salary = " + obj.Salary);

            Console.ReadLine();
        }
    }
       

Output

Name = Ram
Salary = 1000

In C#, it is possible that we can have same or different access modifier for get/set property. 

Is it possible to overridden a function in subclass which is virtual in base class?


Overridden a function in subclass

Yes, to overridden a function in subclass, base class function should be declared as virtual.

Example

// Base class
class Parent
{
    public virtual int Calculation(int i, int j)
    {
        return i * j;
    }
}

 // Derive class
class child : Parent
{
    public override int Calculation(int i, int j)
    {
        return i / j;
    }
}

static void Main(string[] args)
{
    Parent obj = new Parent();
    int i = obj.Calculation(20, 10);
    Console.WriteLine(i);

    Parent obj1 = new child();
    int j = obj1.Calculation(20, 10);
    Console.WriteLine(j);
}

Output

200
2

What is sealed in c#?


Sealed Class

Sealed is the keyword that used with the class to prevent it from Inheritance i.e. no one class can be derived from a sealed class.

Note: Sealed keyword can not be used with the class variables.


Example -

    sealed class MyClass
    {
        public string DisplayName()
        {
            return "Sachin";
        }
    }

    class SealedClass
    {
        static void Main()
        {
             //Correct way to use sealed class.
            MyClass obj = new MyClass();
            Console.WriteLine(obj.DisplayName());

            Console.ReadLine();
        }
    }

     // Not Correct. It will give compilation error.
    class test : MyClass
    {

    }            
 
        Compilation Error - 'WindowsFormsApplication1.test': cannot derive from sealed type 'WindowsFormsApplication1.MyClass' 


Friday, January 11, 2013

Difference between “String” and “Stringbuilder”?

String 

String is immutable and when you do the operation (Insert, Delete and Update) with string object, every time it creates a new memory for the string object.

StringBuilder

StringBuilder is mutable and when you do the operation (Insert, Delete and Update) with StringBuilder object, it doesn’t create a new memory for the StringBuilder object. Every time it updates the same memory so stringBuilder is faster than String.

StringBuilder object is also provide many functions which you can use to do the operations.


Example - String and StringBuilder time difference.           

class StringAndStringBuilder
{
    static void Main()
    {
        string str = string.Empty;

        Stopwatch watch = new Stopwatch();

        watch.Start();
        for (int i = 0; i < 1000; i++)
        {
            str += i.ToString();
        }
        watch.Stop();

        Console.WriteLine("String time in timer ticks :- "+
                            watch.ElapsedTicks.ToString());


        watch.Reset();      
        StringBuilder sb = new StringBuilder();
     
        watch.Start();
        for (int i = 0; i < 1000; i++)
        {
            sb.Append(i.ToString());
        }
        watch.Stop();

        Console.WriteLine("StringBuilder time in timer ticks :- " +
                         watch.ElapsedTicks.ToString());
        Console.ReadLine();

    }
}          

Output

String time in timer ticks :- 17236716

StringBuilder time in timer ticks :- 509064

difference between “Throw” and “Throw ex” in c#?


Throw ex

In Throw ex, the original stack trace information will get override and you will lose the original exception stack trace. I.e. 'throw ex' resets the stack trace.

Throw

In Throw, the original exception stack trace will be retained. To keep the original stack trace information, the correct syntex is 'throw' without specifying an exception.

Example

In the below example, Method2 and Method3 are used 'throw' keyword to re-throwing an exception and Method1 is used 'throw ex'. In the output of this example, you will see that Method2 and Method3 are used 'throw' keyword so stack trace is retained but Method1 used 'throw ex' so In main method stack trace reset and it lose the original stack trace from which the exception was generated.

class ThrowAndThrowEx
{
    static void Main()
    {
        try
        {
            Method1();
        }
        catch (Exception ex)
        {
            Console.WriteLine("\n\n Handling exception in Main().");
            Console.WriteLine("Message :- \n" + ex.Message);
            Console.WriteLine("StackTrace :- \n" + ex.StackTrace);
        }

        Console.ReadLine();
    }

    static void Method1()
    {
        try
        {
            Method2();
        }
        catch (Exception ex)
        {
            Console.WriteLine("\n\n Handling Exception in Method1()");
            Console.WriteLine("Message :- \n" + ex.Message);
            Console.WriteLine("StackTrace :- \n" + ex.StackTrace);
            throw ex;
        }
    }

    static void Method2()
    {
        try
        {
            Method3();
        }
        catch (Exception ex)
        {
            Console.WriteLine("\n\n Handling Exception in Method2()");
            Console.WriteLine("Message :- \n" + ex.Message);
            Console.WriteLine("StackTrace :- \n" + ex.StackTrace);

            throw;
        }
    }

    static void Method3()
    {
        try
        {
            int i = 5;
            int j = 0;
            Console.WriteLine(i / j);
        }
        catch (Exception ex)
        {
            Console.WriteLine("\n\n Handling Exception in Method3()");
            Console.WriteLine("Message :- \n"+ex.Message);
            Console.WriteLine("StackTrace :- \n" + ex.StackTrace);

            throw;
        }
    }
}

Output        

 Handling Exception in Method3()
Message :-
Attempted to divide by zero.
StackTrace :-
   at WindowsFormsApplication1.ThrowAndThrowEx.Method3() in G:\Example\MyTest\Wi
ndowsFormsApplication1\WindowsFormsApplication1\ThrowAndThrowEx.cs:line 62


 Handling Exception in Method2()
Message :-
Attempted to divide by zero.
StackTrace :-
   at WindowsFormsApplication1.ThrowAndThrowEx.Method3() in G:\Example\MyTest\Wi
ndowsFormsApplication1\WindowsFormsApplication1\ThrowAndThrowEx.cs:line 69
   at WindowsFormsApplication1.ThrowAndThrowEx.Method2() in G:\Example\MyTest\Wi
ndowsFormsApplication1\WindowsFormsApplication1\ThrowAndThrowEx.cs:line 45


 Handling Exception in Method1()
Message :-
Attempted to divide by zero.
StackTrace :-
   at WindowsFormsApplication1.ThrowAndThrowEx.Method3() in G:\Example\MyTest\Wi
ndowsFormsApplication1\WindowsFormsApplication1\ThrowAndThrowEx.cs:line 69
   at WindowsFormsApplication1.ThrowAndThrowEx.Method2() in G:\Example\MyTest\Wi
ndowsFormsApplication1\WindowsFormsApplication1\ThrowAndThrowEx.cs:line 52
   at WindowsFormsApplication1.ThrowAndThrowEx.Method1() in G:\Example\MyTest\Wi
ndowsFormsApplication1\WindowsFormsApplication1\ThrowAndThrowEx.cs:line 30


 Handling exception in Main().
Message :-
Attempted to divide by zero.
StackTrace :-
   at WindowsFormsApplication1.ThrowAndThrowEx.Method1() in G:\Example\MyTest\Wi
ndowsFormsApplication1\WindowsFormsApplication1\ThrowAndThrowEx.cs:line 37
   at WindowsFormsApplication1.ThrowAndThrowEx.Main() in G:\Example\MyTest\Windo
wsFormsApplication1\WindowsFormsApplication1\ThrowAndThrowEx.cs:line 14
       

Sunday, January 6, 2013

Deferred Execution and Immediate Execution in c#?


Deferred Execution and Immediate Execution

To understand the Deferred Execution and Immediate Execution, first we have a look on “How LINQ query execute”.
A LINQ query has three operations to execute:

  • Get the data source
  • Create the LINQ query
  • Execute the query


Example

        static void Main()
        {
            // Employee Salary data source
            List empSalary = new List { 3500, 2400, 8500, 6800, 7500, 9500, 2800, 6500, 4500, 7000 };

            // LINQ query
            IEnumerable decendingSalary = from i in empSalary 
                                               orderby i
                                               select i;

            //Execute Query (Deferred Execution)
            foreach (int salary in decendingSalary)
            {
                Console.WriteLine(salary);
            }

            Console.ReadLine();
        }

Result

2400
2800
3500
4500
6500
6800
7000
7500
8500
9500

The above LINQ query execution is called deferred execution.

Sometime you need query result count, min number and max number etc. to get the number count or min max number you have to use Count, MIN and MAX method. This execution is called immediate execution.

        static void Main()
        {
            // Employee Salary data source
            List empSalary = new List { 3500, 2400, 8500, 6800, 7500, 9500, 2800, 6500, 4500, 7000 };

            // LINQ query
            var decendingSalary = from i in empSalary 
                                               orderby i
                                               select i;
            //Immediate Execution
            int maxNumber = decendingSalary.Max();
            Console.WriteLine(maxNumber);

            Console.ReadLine();
        }

Result

9500


Difference between Delegate and Events in C#?

Delegate:

A delegate in C# is similar to a function pointer in C. A delegate object holds the reference of one or more methods. Delegate creation is the four steps process.

  • Declaration of delegate
  • Delegate object creation
  • Point the reference to the method.
  • Invoke delegate

A delegate object doesn't care about the class in which the function exists. There is only one restriction that the delegate signature and the function signature should be same otherwise delegate object can’t hold the reference of the method which doesn't have the same signature. Signature means return type and parameters.

Example
public class Math
    {
        public static int Add(int i, int j)
        {
            return i + j;
        }
    }

    class DelegateAndEvent
    {
        //Delegate Declaration
        public delegate int MathFunctions(int i, int j);

        static void Main()
        {
            //Delegate object creation.
            MathFunctions MathFun = null;

            //Point the reference to the method.
            MathFun += Math.Add;

           // Invoke delegate.
            int value = MathFun.Invoke(10, 20);
            Console.WriteLine(value.ToString());

            Console.ReadLine();
        }
    }

Events:


Event is a mechanism by which a class can send notification to its client. For example, you have an application to perform certain operation, if an operation is failed then the application send the notification to log file, printer, fax, email etc. 

Events are declared using delegates. Without delegate, we can not create Events.

Example

    //subscriber class
    public class LogFileNotification
    {
        //Constructor 
        public LogFileNotification(Operatinos obj)
        {
            obj.SendNotification += WriteLog;           
        }

        private void WriteLog(string message)
        {
            //Write Log into a file
            Console.WriteLine("WriteLog :- " + message);
        }
    }

    //subscriber class
    public class PrinterNotification
    {
        //Constructor
        public PrinterNotification(Operatinos obj)
        {
            obj.SendNotification += PrintFailure;
        }

        private void PrintFailure(string message)
        {
           // Print the failure text. 
            Console.WriteLine("PrintFailure :- " + message);
        }
    }

    //subscriber class
    public class FaxNotification
    {
        //Constructor
        public FaxNotification(Operatinos obj)
        {
            obj.SendNotification += SendFax;
        }

        private void SendFax(string message)
        {
            // Send Fax to appropriate person.
            Console.WriteLine("SendFax :- " + message);
        }
    }

    //subscriber class
    public class EmailNotification
    {
        //Constructor
        public EmailNotification(Operatinos obj)
        {
            obj.SendNotification += SendEmail;
        }

        public void SendEmail(string message)
        {
            // Send email to appropriate person.
            Console.WriteLine("EmailNotification :- " + message);
        }
    }


    //Publisher class
    public class Operatinos
    {
        public delegate void Notification(string str);
        public event Notification SendNotification;
        LogFileNotification logFileNotification = null;
        PrinterNotification printerNotification = null;
        FaxNotification faxNotification = null;
        EmailNotification emailNotification = null;

       //Constructor
        public Operatinos()
        {
            logFileNotification = new LogFileNotification(this);
            printerNotification = new PrinterNotification(this);
            faxNotification = new FaxNotification(this);
            emailNotification = new EmailNotification(this);
        }

        public void OperationFailed()
        {
            SendNotification("Operation is failed.");
        }
    }

    public class MainClass
    {
        static void Main()
        {
            Operatinos op = new Operatinos();
            op.OperationFailed();

            Console.ReadLine();
        }
    }


Output

WriteLog :- Operation is failed.
PrintFailure :- Operation is failed.
SendFax :- Operation is failed.
EmailNotification :- Operation is failed.

The above example is based on publisher subscription model and we have achieved publisher subscription model through events. But the same things we can also achieved through delegate. Now the question comes, What is the main difference between Delegate and Events?

Main difference between Delegate and Events?

If we create a delegate into publisher class then subscriber has the authority todo the multiple operations on the delegate. It can invoke the delegate; can make the clone of the delegate and other operation also. See the below image.



































But if we create Events into publisher class then subscriber class doesn't has any authority to do the operation. See the below image.