Sunday, April 29, 2012

OOP


Object Oriented Programming :- A technique to think real world in terms of object.

Class :- It is a definition, contains variable, method, property, events etc.

Object :- The physical representation of data based on the class.


Fields :- Fields of the class are like variables and they can read and set.


Property :-  They retrieve and set like fields but implement using property get and set.


Method :- It represents the object’s built in procedure.


Events :- It allow object to perform action towards specific occurrence. Or in other word, events are certainly action that happens during the execution of a program that the application wishes to be notified about, so it can respond.


Data Abstraction :- Providing functionality to the user without showing the complexity of implementation.


Data Encapsulation :-  A process of hiding all the internal details of an object from outside world.


Structure :- A tool for handling a group of logically related data items. Structure are value type and allocated on the stack.


Constructor :- A subprogram of the class, which will be called implicitly before creating object of the class.


Destructor :- It runs when an object is destroyed. In destructor we can place code to clean up the object after it is used, i.e, Finalize method.


Abstract Class :- The class which is not used to create object. An abstract class is design to act as a base class(to be inherited by other class). It is similar to interface.


Delegate :- A class that can hold a reference to a method or a function. Delegate class has signature and it can only reference those methods whose signature is compliant with the class.


Shadowing :- When two element in a program have same name. One of them can hide and shadow the other.


Collection classes :-
Queue, Stack, BitArray, HashTable, LinkedList, ArrayList, NameValueCollection, Array, SortedList, HybridDictionary, ListDictionary, StringCollection, StringDictionary


A constructor can be private :-
True, A constructor can be private. We can declare a constructor as private.


Operators that cannot be overloaded :-
sizeof
.
.*
.->
::
?:


Static methods can not use non static members :- True


Static datamembers should be initialized inside the constructor :-
False, Static datamembers should not be initialised inside constructor.


Why can't you specify the accessibility modifier for methods inside the interface :-
You are not allowed to specify any accessibility, it's public by default.


Allow class to be inherited, but prevent the method from being over-ridden :-
Yes, just leave the class public and make the method sealed.


Can you prevent your class from being inherited and becoming a base class for some other classes :-
Yes, that's what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It's the same concept as final class in Java.


Can you override private virtual methods :-
No, you cannot access private methods in inherited classes.


Can you declare the override method static while the original method is non-static :-
No, you can't, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.


How's method overriding different from overloading :-
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.


Early binding vs late binding :-
Calling a non-virtual method, decided at a compile time is known as early binding. Calling a virtual method (Pure Polymorphism), decided at a runtime is known as late binding.


Diversities between an abstract method & virtual method :-
An Abstract method does not provide an implementation and forces overriding to the deriving class (unless the deriving class also an abstract class), where as the virtual method has an implementation and leaves an option to override it in the deriving class. Thus Virtual method has an implementation & provides the derived class with the option of overriding it. Abstract method does not provide an implementation & forces the derived class to override the method.


When to Use Abstract Classes and When Interfaces :-
If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.


Constructors :-
Constructors are used for initializing the members of a class whenever an object is created with the default values for initialization.
If no constructor defined then the CLR will provide an implicit constructor which is called as Default Constructor.
A class can have any number of constructors provided they vary with the number of arguments that are passed, which is they should have different signatures.
Constructors do not return a value, they can be overloaded

Types of Constructors :-
Public : Accessible to All
Private: Those classes in which only static members are there and you don't want there objects to be created in any class.
Static: Used for initializing only the static members of the class. These will be invoked for the very first time the class is being loaded on the memory. They cannot accept any arguments. Static Constructors cannot have any access modifiers.
Intern: implementations of the abstract class to the assembly defining the class.

Interface vs Abstract Class :-
Abstract Class,
Have constructors
Not necessarily for the class inheriting it to Implement all the Methods
Doesn't Support Multiple Inheritance
this can contain access modifiers for the subs, functions, properties
Fast
An abstract class can have fields and constants defined
Interface,
Doesn't have constructors
necessary to implement all the methods
support multiple inheritance
cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
Requires more time to find the actual method in the corresponding classes.
No fields can be defined in interfaces

What can you do to make class available for inheritance but you need to prevent it's method to come in inheritance chain :-
Well, Declare a class with public access specifier and mark all it's method to sealed . As anything which is declared with sealed keyword cannot be inherited.

Attributes in .Net :-
An Attribute is a declarative tag which can be used to provide information to the compiler about the behaviour of the C# elements such as classes and assemblies.
C# provides convenient technique that will handle tasks such as performing compile time operations , changing the behaviour of a method at runtime or maybe even handle unmanaged code.
- Obsolete
- WebMethod

Can we declare private class in a Namespace :-
No. If you try to create a private class in a Namespace, Compiler will throw a compile time error “Namespace elements cannot be explicitly declared as private, protected, or protected internal”.

new keyword vs override :-
new: hides the base class function.
Override: overrides the base class function.

Default Access modifiers in C# :-
An enum has default modifier as public
A class has default modifiers as private .
An interface has default modifier as public
A struct has default modifier as private

Pure virtual function :-
A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be "pure" using the curious "=0"
syntax:
class Base {
public:
void f1(); // not virtual
virtual void f2(); // virtual, not pure
virtual void f3() = 0; // pure virtual
};

Sealed modifiers :-
Sealed types cannot be inherited & are concrete. Sealed modifiers can also be applied to instance methods, properties, events & indexes.

Virtual keyword :-
This keyword indicates that a member can be overridden in a child class. It can be applied to methods, properties, indexes and events.

Static field :-
To indicate that a field should only be stored once no matter how many instance of the class we create.

Class :-
A user-defined data structure that groups properties and methods. Class doesn’t occupies memory.

Object :-
Instance of Class is called object. An object is created in memory using keyword “new”.

Struct and Class :-
• Struct are Value type and are stored on stack, while Class are Reference type and are stored on heap.
• Struct “do not support” inheritance, while class supports inheritance. However struct can implements interface.
• Struct should be used when you want to use a small data structure, while Class is better choice for complex data structure.

Difference between instantiating structures with and without using the new keyword :-
When a structure is instantiated using the new keyword, a constructor (no-argument or custom, if provided) is called which initializes the fields in the structure. When a structure is instantiated without using the new keyword, no constructor is called. Hence, one has to explicitly initialize all the fields of the structure before using it when instantiated without the new keyword.

Value Type and Reference Type :-
A variable is value type or reference type is solely determined by its data type.
Eg: int, float, char, decimal, bool, decimal, struct, etc are value types, while object type such as class, String, Array, etc are reference type.

ref and out keyword :-
ref keyword,
Passing variables by value is the default. However, we can force the value parameter to be passed by reference. Note: variable “must” be initialized before it is passed into a method.
out keyword,
out keyword is used for passing a variable for output purpose. It has same concept as ref keyword, but passing a ref parameter needs variable to be initialized while out parameter is passed without initialized.
It is useful when we want to return more than one value from the method.

System.String vs System.Text.StringBuilder classes :-
System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

System.Array.CopyTo() and System.Array.Clone() :-
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array.  The CopyTo() method copies the elements into another existing array.  Both perform a shallow copy.  A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array.  A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.

const vs. readonly :-
const,
A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared. For example;
public class MyClass
{
    public const double PI = 3.14159;
}
PI cannot be changed in the application anywhere else in the code as this will cause a compiler error. Constants must be a value type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool), an enumeration, a string literal, or a reference to null.
readonly,
A read only member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared. For example:
public class MyClass
{
    public readonly double PI = 3.14159;
}
or
public class MyClass
{
    public readonly double PI;
    public MyClass()
    {
        PI = 3.14159;
    }
}
Because a readonly field can be initialized either at the declaration or in a constructor, readonly fields can have different values depending on the constructor used.

Empty & Null String: An empty string is an instance of a System.String object that contains zero characters. Empty strings are used quite commonly in various programming scenarios to represent a blank text field. You can call methods on empty strings because they are valid System.String objects. By contrast, a null string does not refer to an instance of a System.String object and any attempt to call a method on a null string results in a NullReferenceException. However, you can use null strings in concatenation and comparison operations with other strings.
using System;
class Class1
{
    class mainClass
    {
        [STAThread]
        static void Main(string[] args)
        {
            string s1 = "Hello";
            string s2 = s1;
            s1 += " and goodbye.";
            Console.WriteLine(s2); //outputs "Hello"
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("one ");
            sb.Append("two ");
            sb.Append("three");
            string str = sb.ToString();
            //loop with string
            string s5 = "Printing backwards";
            for (int i = 0; i < s5.Length; i++)
            {
                System.Console.Write(s5[s5.Length - i - 1]);  // outputs "sdrawkcab gnitnirP"
            }
            //strinng with split
            char[] delimit = new char[] { ' ' };
            string s10 = "The cat sat on the mat.";
            foreach (string substr in s10.Split(delimit))
            {
                System.Console.WriteLine(substr);
            }
            System.Text.StringBuilder sbd = new System.Text.StringBuilder("Rat: the ideal pet");
            sbd[0] = 'C';
            System.Console.WriteLine(sbd.ToString());
            Console.ReadLine();
        }
    }
}

Array:
An array is a data structure that contains a number of variables of the same type.
An array can be Single-Dimensional, Multidimensional or Jagged.
The default value of numeric array elements are set to zero, and reference elements are set to null.
A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.
Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.
Array elements can be of any type, including an array type.
Array types are reference types derived from the abstract base type Array. Since this type implements IEnumerable and IEnumerable, you can use foreach iteration on all arrays in C#.
using System;
class Class1
{
    class mainClass
    {
        [STAThread]
        static void Main(string[] args)
        {
            // Declare a single-dimensional array
            int[] array1 = new int[5];
            // Declare and set array element values
            int[] array2 = new int[] { 1, 3, 5, 7, 9 };
            // Alternative syntax
            int[] array3 = { 1, 2, 3, 4, 5, 6 };
            // Declare a two dimensional array
            int[,] multiDimensionalArray1 = new int[2, 3];
            // Declare and set array element values
            int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };
            // Declare a jagged array
            int[][] jaggedArray = new int[6][];
            // Set the values of the first array in the jagged array structure
            jaggedArray[0] = new int[4] { 1, 2, 3, 4 };
            jaggedArray[1] = new int[5] { 1, 2, 3, 4, 5 };
        }
    }
}

Boxing – UnBoxing:
Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a Value Types to the type object or to any interface type implemented by this value type.
Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface.
using System;
class Class1
{
    class mainClass
    {
        /// <summary>
        /// STAThread - for single threaded application, console application attribute
        /// </summary>
        /// <param name="args"></param>
        [STAThread]
        static void Main(string[] args)
        {
            int s = 123;
            object o = s;  // implicit boxing
            try
            {
                int j = (int)o;  // attempt to unbox
                Console.WriteLine("Unboxing OK.");
            }
            catch (System.InvalidCastException e)
            {
                Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
            }
            Console.ReadLine();
        }
    }
}

Partial Class:
It is possible to split the definition of a class or a struct, or an interface over two or more source files.
When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously.
Each source file contains a section of the class definition, and all parts are combined when the application is compiled.
partial method doesn't allow access modifier.
using System;
class Class1
{
    class mainClass
    {
        /// <summary>
        /// STAThread - for single threaded application, console application attribute
        /// </summary>
        /// <param name="args"></param>
        [STAThread]
        static void Main(string[] args)
        {
            #region partial class call
            CoOrdsPC myCoOrds = new CoOrdsPC(10, 15);
            myCoOrds.PrintCoOrds();
            Console.ReadLine();
            #endregion
        }
        public partial class CoOrdsPC
        {
            private int xi;
            private int yi;
            public CoOrdsPC(int x, int y)
            {
                this.xi = x;
                this.yi = y;
            }
            partial void printsome();
        }
        public partial class CoOrdsPC
        {
            public void PrintCoOrds()
            {
                Console.WriteLine("CoOrds: {0},{1}", xi, yi);
            }
            partial void printsome()
            {
            }
        }
    }
}

Structure(struct):
Structs are value types — when an object is created from a struct and assigned to a variable, the variable contains the entire value of the struct. Structs cannot inherit from classes or other structs.
When you create a struct object using the new operator, it gets created and the appropriate constructor is called.
Unlike classes, structs can be instantiated without using the new operator.
Within a struct declaration, fields cannot be initialized unless they are declared as const or static.
A struct may not declare a default constructor — a constructor with no parameters — or a destructor.
using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        // Initialize:  
        CoOrds coords1 = new CoOrds();
        CoOrds coords2 = new CoOrds(10, 10);
        // Display results:
        Console.Write("CoOrds 1: ");
        Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y);
        Console.Write("CoOrds 2: ");
        Console.WriteLine("x = {0}, y = {1}", coords2.x, coords2.y);
        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
    public struct CoOrds
    {
        public int x, y;
        public CoOrds(int p1, int p2)
        {
            x = p1;
            y = p2;
        }
    }
}

Polymorphism:
Poly means many and morph means form. The process of create more than one function with same name but different argument list.
The new keyword is used to create a new definition of that method, field, or property on a derived class.
When the new keyword is used, the new class members are called instead of the base class members that have been replaced. Those base class members are called hidden members.
Fields cannot be virtual; only methods, properties, events and indexers can be virtual.
A derived class can stop virtual inheritance by declaring an override as sealed.
Sealed methods can be replaced by derived classes using the new keyword.
Run time Polymorphism: Same function implements different tasks by virtual and override. Virtual – To hide existing class method. Override – Enable OR implement current class method.

Types of Polymorphism:
1. Compile time (Static): Function Overloading
2. Run time (Dynamic): Function Overriding, Virtual functions
Compile time have 3 types:
I. Constructor overloading(i.e.,with same constructor name and different no of arguments or different data types or both )
II Function overloading(i.e.,with same function name and different no of arguments or different data types or both)
III. Operator overloading: exaample : String s = "James";
s = s + "Bond";
using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        //compiletime-polymorphism : Function overloading comes under compile time polymorphism
        Console.WriteLine("Press 1 to select multiply of two numbers or Press 2 to select multiply of three numbers");
        int press = 0;
        press = Convert.ToInt16(Console.ReadLine());
        Console.WriteLine("Enter first number for multiplication");
        int number_one = Convert.ToInt16(Console.ReadLine());
        Console.WriteLine("Enter second number for multiplication");
        int number_two = Convert.ToInt16(Console.ReadLine());
        int number_three = 0;
        if (press == 2)
        {
            Console.WriteLine("Enter third number for multiplication");
            number_three = Convert.ToInt16(Console.ReadLine());
        }
        Calculation objcal = new Calculation();
        double getResult = 0;
        if (press == 1)
        {
            getResult = objcal.Multiply(number_one, number_two);
        }
        else
        {
            getResult = objcal.Multiply(number_one, number_two, number_three);
        }
        Console.WriteLine("Result: " + getResult);
        Console.ReadKey();
        //runtime-polymorphism : function overriding, virtual functions come under runtime polymorphism
        Shapes objshapes = new Prisms();
        objshapes.getVolume();
        Console.ReadLine();
    }
}
class Calculation
{
    double result = 0;
    public double Multiply(int x, int y)
    {
        result = x * y;
        return result;
    }
    public double Multiply(int x, int y, int z)
    {
        result = x * y * z;
        return result;
    }
}
class Shapes
{
    public virtual void getArea()
    {
        Console.WriteLine("get area  formula for different shapes");
    }
    public virtual void getVolume()
    {
        Console.WriteLine("get volume formula for different shapes");
    }
}
class Circle : Shapes
{
    public override void getArea()
    {
        Console.WriteLine("Area of circle is 3.14 * radius * radius");
    }
}
class Prisms : Shapes
{
    public override void getVolume()
    {
        Console.WriteLine("Volume of Prisms is breath * height");
    }
}
class Pyramid : Shapes
{
    public override void getVolume()
    {
        Console.WriteLine("Volume of Pyramid is 1/3 breath * height");
    }
}

Event:
using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        Publisher pub = new Publisher();
        Subscriber sub1 = new Subscriber("sub1", pub);
        Subscriber sub2 = new Subscriber("sub2", pub);
        // Call the method that raises the event.
        pub.DoSomething();
        // Keep the console window open
        Console.WriteLine("Press Enter to close this window.");
        Console.ReadLine();
    }
    // Define a class to hold custom event info
    public class CustomEventArgs : EventArgs
    {
        public CustomEventArgs(string s)
        {
            message = s;
        }
        private string message;
        public string Message
        {
            get { return message; }
            set { message = value; }
        }
    }
    // Class that publishes an event
    class Publisher
    {
        // Declare the event using EventHandler<T>
        public event EventHandler<CustomEventArgs> RaiseCustomEvent;
        public void DoSomething()
        {
            // Write some code that does something useful here
            // then raise the event. You can also raise an event
            // before you execute a block of code.
            OnRaiseCustomEvent(new CustomEventArgs("Did something"));
        }
        // Wrap event invocations inside a protected virtual method
        // to allow derived classes to override the event invocation behavior
        protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
        {
            // Make a temporary copy of the event to avoid possibility of
            // a race condition if the last subscriber unsubscribes
            // immediately after the null check and before the event is raised.
            EventHandler<CustomEventArgs> handler = RaiseCustomEvent;
            // Event will be null if there are no subscribers
            if (handler != null)
            {
                // Format the string to send inside the CustomEventArgs parameter
                e.Message += String.Format(" at {0}", DateTime.Now.ToString());
                // Use the () operator to raise the event.
                handler(this, e);
            }
        }
    }
    //Class that subscribes to an event
    class Subscriber
    {
        private string id;
        public Subscriber(string ID, Publisher pub)
        {
            id = ID;
            // Subscribe to the event using C# 2.0 syntax
            pub.RaiseCustomEvent += HandleCustomEvent;
        }
        // Define what actions to take when the event is raised.
        void HandleCustomEvent(object sender, CustomEventArgs e)
        {
            Console.WriteLine(id + " received this message: {0}", e.Message);
        }
    }
}

Nullable:
Nullable types are instances of the System.Nullable struct.
A nullable type can represent the normal range of values for its underlying value type, plus an additional null value.
using System;
class Class1
{
    void main()
    {
        int? num = null;
        if (num.HasValue == true)
        {
            Console.WriteLine("num = " + num.Value);
        }
        else
        {
            Console.WriteLine("num = Null");
        }
        //y is set to zero
        int y = num.GetValueOrDefault();
        // num.Value throws an InvalidOperationException if num.HasValue is false
        try
        {
            y = num.Value;
        }
        catch (InvalidOperationException e)
        {
            Console.WriteLine(e.Message);
        }
        Console.ReadLine();
    }
}

Operator overload:
C# allows user-defined types to overload operators by defining static member functions using the operator keyword.
using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        Complex num1 = new Complex(2, 3);
        Complex num2 = new Complex(3, 4);
        // Add two Complex objects 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.ReadLine();
    }
    public struct Complex
    {
        public int real;
        public int imaginary;
        public Complex(int real, int imaginary)  //constructor
        {
            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 a complex number in the traditional format:
        public override string ToString()
        {
            return (System.String.Format("{0} + {1}i", real, imaginary));
        }
    }
}

Interface:
Interfaces can be made up of methods, properties, events, indexers, or any combination of those four member types. An interface cannot contain fields. Interfaces members are automatically public. A class or struct can inherit more than one interface.
When a class or struct inherits an interface, it inherits only the method names and signatures, because the interface itself contains no implementations.
To implement an interface member, the corresponding member on the class must be public, non-static, and have the same name and signature as the interface member.
an interface may declare a property with a get accessor, but the class implementing the interface can declare the same property with both a get and set accessor.
Interfaces can inherit other interfaces. It is possible for a class to inherit an interface multiple times, through base classes or interfaces it inherits.
using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        Whale whale = new Whale();
        Human human = new Human();
        /// The human object is casted to the interface type
        IIntelligence humanIQ = (IIntelligence)human;
        humanIQ.intelligent_behavior();
        Console.ReadLine();
    }
    public class Mammal
    {
        protected string Characteristis;
        public string characteristics
        {
            get
            {
                return this.Characteristis;
            }
            set
            {
                this.Characteristis = value;
            }
        }
    }
    interface IIntelligence
    {
        /// Interface method declaration
        bool intelligent_behavior();
        void same();
    }
    interface IDesire
    {
        void same();
    }
    class Human : Mammal, IIntelligence, IDesire
    {
        public Human()
        {
            characteristics = "Human are mammals";
        }
        /// Interface method definition in the class that implements it
        public bool intelligent_behavior()
        {
            Console.WriteLine("{0} and have intelligence", characteristics);
            return true;
        }
        //implement same method for both interface
        public void same()
        {
            Console.WriteLine("with brain");
        }
    }
    class Whale : Mammal, IDesire
    {
        public Whale()
        {
            characteristics = "Whale are mammals";
            Console.WriteLine("{0}", characteristics);
        }
        void IDesire.same()
        {
            Console.WriteLine("without brain");
        }
    }
}

Abstract class:
Classes can be declared as abstract. This is accomplished by putting the keyword abstract before the keyword class in the class definition. An abstract class cannot be instantiated.
The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
Abstract classes may also define abstract methods. Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block.
Derived classes of the abstract class must implement all abstract methods. When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method.
If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. Abstract method can't be private or static.
using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        //You can create an instance of the derived class
        absDerived calculate = new absDerived();
        int added = calculate.AddTwoNumbers(10, 20);
        int multiplied = calculate.MultiplyTwoNumbers(10, 20);
        Console.WriteLine("Added : {0}, Multiplied : {1}", added, multiplied);
        Console.ReadLine();
    }
    //Creating an Abstract Class
    abstract class absClass
    {
        //A Non abstract method
        public int AddTwoNumbers(int Num1, int Num2)
        {
            return Num1 + Num2;
        }
        //An abstract method, to be overridden in derived class
        public abstract int MultiplyTwoNumbers(int Num1, int Num2);
        //An abstract property
        protected int myNumber;
        public abstract int numbers
        {
            get;
            set;
        }
    }
    class absDerived : absClass
    {
        //using override keyword, implementing the abstract method MultiplyTwoNumbers
        public override int MultiplyTwoNumbers(int Num1, int Num2)
        {
            return Num1 * Num2;
        }
        //Implementing abstract properties
        public override int numbers
        {
            get
            {
                return myNumber;
            }
            set
            {
                myNumber = value;
            }
        }
    }
}

Constructor:
A sub program of class, which will be called implicitly before creating the object of the class. It is a special method. Both classes and structs can define constructors that take parameters.
Constructors have the same name as the class, and usually initialize the data members of the new object.
if you don't use an access modifier with the constructor it will still be private by default.
default constructor: A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated using the new operator and no arguments are provided to new.
Unless the class is static, classes without constructors are given a public default constructor by the C# compiler in order to enable class instantiation.
Constructors for struct types are similar to class constructors, but structs cannot contain an explicit default constructor because one is provided automatically by the compiler.
using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        Manager t = new Manager(2000);
        Console.WriteLine("Salary is {0}", t.salary);
        Console.ReadLine();
    }
    public class Employee
    {
        public int salary;
        public Employee()
        {
            salary = 0;
        }
        /// parameter constructor
        public Employee(int annualSalary)
        {
            salary = annualSalary;
        }
        public Employee(int weeklySalary, int numberOfWeeks)
        {
            salary = weeklySalary * numberOfWeeks;
        }
    }
A constructor can use the base keyword to call the constructor of a base class. The constructor for the base class is called before the block for the constructor is executed. The base keyword can be used with or without parameters.
Instance constructors are used to create and initialize instances. Instance constructors can also be used to call the instance constructors of base classes.
A constructor can invoke another constructor in the same object using the this keyword.
    public class Manager : Employee
    {
        /// <summary>
        /// </summary>
        /// <param name="annualSalary"></param>
        public Manager(int annualSalary)
            : base(annualSalary)
        {
            //Add further instructions here.
        }
        public Manager(int annualSalary, int empId)
            : this(2000)
        {
            //Add further instructions here.
        }

Copy Constructor: 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.
        public Manager(Manager previousManager)
        {
            salary = previousManager.salary;
        }
    }
}

Private Constructor: A private constructor is a special instance constructor. It is commonly used in classes that contain static members only.
If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.
The declaration of the empty constructor prevents the automatic generation of a default constructor.
If you don't use an access modifier with the constructor it will still be private by default.
Private constructors are used to prevent the creation of instances of a class when there are no instance fields or methods.
class NLog
{
    private NLog() { }
    public static double e = System.Math.E;  //2.71828...
}

Static Constructor:  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.
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.
public class Bus
{
    // Static constructor:
    static Bus()
    {
        System.Console.WriteLine("The static constructor invoked.");
    }
    public static void Drive()
    {
        System.Console.WriteLine("The Drive method invoked.");
    }
}

Destructor:
Destructors are used to destruct instances of classes. Destructors cannot be defined in structs. They are only used with classes. A class can only have one destructor.
Destructors cannot be inherited or overloaded. Destructors cannot be called. They are invoked automatically. A destructor does not take modifiers or have parameters.
So, what do you do if you want to call the destructors once you are finished using the object? There are two ways: Call the Garbage collector to clean up. or Implement Dispose method of IDisposable interface.
using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        C c = new C();
        Console.WriteLine("Object Created ");
        Console.WriteLine("Press enter to Destroy it");
        Console.ReadLine();
        c = null;
        //GC.Collect();
    }
}
class A
{
    public A()
    {
        Console.WriteLine("Creating A");
    }
    ~A()
    {
        Console.WriteLine("Destroying A");
    }
}
class B : A
{
    public B()
    {
        Console.WriteLine("Creating B");
    }
    ~B()
    {
        Console.WriteLine("Destroying B");
    }
}
class C : B
{
    public C()
    {
        Console.WriteLine("Creating C");
    }
    ~C()
    {
        Console.WriteLine("Destroying C");
    }
}

Delegate:
A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method.
The type of a delegate is defined by the name of the delegate. Delegates allow methods to be passed as parameters.
Delegates have internal access by default. A delegate is a type that defines a method signature. When you instantiate a delegate, you can associate its instance with any method with a compatible signature.
Delegates are used to pass methods as arguments to other methods. Delegates are like C++ function pointers but are type safe.

Multicast Delegate: This delegate can point to any method, taking two integers and returning an integer.
It is a delegate which holds the reference of more than one method. Multicast delegates must contain only methods that return void, else there is a run-time exception.
using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        myDelegate del = new myDelegate(CalculationD.Add);
        int addResult = del(5, 5);
        Console.WriteLine("5 + 5 = {0}\n", addResult);
        myDelegate del1 = new myDelegate(CalculationD.Multiply);
        int mulResult = del1(5, 6);
        Console.WriteLine("5 X 5 = {0}", mulResult);
        Console.ReadLine();
    }
    public delegate int myDelegate(int x, int y);
    public class CalculationD
    {
        public static int Add(int x, int y)
        {
            return x + y;
        }
        public static int Subtract(int x, int y)
        {
            return x - y;
        }
        public static int Multiply(int x, int y)
        {
            return x * y;
        }
    }
}

Indexer:
Indexers are a syntactic convenience that enable you to create a class, struct, or interface that client applications can access just as an array.
An indexer is accessed using the [] operator, it does not have a name.
Indexer an object to be indexed in the same way as an array.
Indexer modifier can be private, public, protected or internal.
It can Accessed through an index.
using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        parentClass objI = new parentClass();
        objI[0] = "ONE";
        objI[1] = "TWO";
        objI[2] = "THREE";
        objI[3] = "FOUR ";
        objI[4] = "FIVE";
        Console.WriteLine("{0},\n{1},\n{2},\n{3},\n{4}\n", objI[0], objI[1], objI[2], objI[3], objI[4]);
        Console.ReadLine();
    }
    class parentClass
    {
        private string[] range = new string[5];
        public string this[int indexrange]
        {
            get
            {
                return range[indexrange];
            }
            set
            {
                range[indexrange] = value;
            }
        }
    }
}

Iterator:
An iterator is a method, get accessor or operator that enables you to support foreach iteration in a class or struct without having to implement the entire IEnumerable interface.
When the compiler detects your iterator, it will automatically generate the Current, MoveNext and Dispose methods of the IEnumerable or IEnumerable<T> interface.
An iterator is a section of code that returns an ordered sequence of values of the same type. An iterator can be used as the body of a method, an operator, or a get accessor.
The iterator code uses the yield return statement to return each element in turn. yield break ends the iteration. Multiple iterators can be implemented on a class. Each iterator must have a unique name just like any class member.
The yield keyword is used to specify the value, or values, returned. When the yield return statement is reached, the current location is stored. Execution is restarted from this location the next time the iterator is called.
An iterator is a section of code that returns an ordered sequence of values. The interator code uses the yield return statement to return each element in turn.
using System;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        // Create an instance of the collection class
        DaysOfTheWeek week = new DaysOfTheWeek();
        // Iterate with foreach
        foreach (string day in week)
        {
            Console.Write(day + " ");
        }
        Console.ReadLine();
    }
    public class DaysOfTheWeek : System.Collections.IEnumerable
    {
        string[] m_Days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };
        public System.Collections.IEnumerator GetEnumerator()
        {
            for (int i = 0; i < m_Days.Length; i++)
            {
                yield return m_Days[i];
            }
        }
    }
}

Multi thread:
using System;
using System.Collections.Generic;
using System.Threading;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        MultiThread c1 = new MultiThread();
        Console.ReadLine();
        c1.StopThreads = true;
    }
    class MultiThread
    {
        private bool _stopThreads = false;
        public bool StopThreads
        {
            set
            {
                _stopThreads = value;
            }
        }
        // shared memory variable between the two threads
        private string _threadOutput = "";
        /// <summary>
        /// Thread 1, Displays that we are in thread 1
        /// </summary>
        void DisplayThread1()
        {
            while (_stopThreads == false)
            {
                lock (this)
                {
                    Console.WriteLine("Display Thread 1");
                    _threadOutput = "Hello Thread1";
                    Thread.Sleep(1000);  // simulate a lot of processing
                    // tell the user what thread we are in thread #1
                    Console.WriteLine("Thread 1 Output --> {0}", _threadOutput);
                }
            }
        }
        /// <summary>
        /// Thread 2, Displays that we are in thread 2
        /// </summary>
        void DisplayThread2()
        {
            while (_stopThreads == false)
            {
                lock (this)
                {
                    Console.WriteLine("Display Thread 2");
                    _threadOutput = "Hello Thread2";
                    Thread.Sleep(1000);  // simulate a lot of processing
                    // tell the user we are in thread #2
                    Console.WriteLine("Thread 2 Output --> {0}", _threadOutput);
                }
            }
        }
        AutoResetEvent _blockThread1 = new AutoResetEvent(false);
        AutoResetEvent _blockThread2 = new AutoResetEvent(true);
        void DisplayThread_1()
        {
            while (_stopThreads == false)
            {
                // block thread 1  while the other is executing
                _blockThread1.WaitOne();
                // Set was called to free the block on thread 1, continue executing the code
                Console.WriteLine("Display Thread 1");
                _threadOutput = "Hello Thread 1";
                Thread.Sleep(1000);  // simulate a lot of processing
                // tell the user what thread we are in thread #1
                Console.WriteLine("Thread 1 Output --> {0}", _threadOutput);
                // finished executing the code in thread 1, so unblock thread 2
                _blockThread2.Set();
            }
        }
        /// <summary>
        /// Thread 2, Displays that we are in thread 2
        /// </summary>
        void DisplayThread_2()
        {
            while (_stopThreads == false)
            {
                // block thread 2  while the other is executing
                _blockThread2.WaitOne();
                // Set was called to free the block on thread 2, continue executing the code
                Console.WriteLine("Display Thread 2");
                _threadOutput = "Hello Thread 2";
                Thread.Sleep(1000);  // simulate a lot of processing
                // tell the user we are in thread #2
                Console.WriteLine("Thread 2 Output --> {0}", _threadOutput);
                // finished executing the code in thread 2, so unblock thread 1
                _blockThread1.Set();
            }
        }
        public MultiThread()
        {
            // set up and start threads;
            Thread thread1 = new Thread(new ThreadStart(DisplayThread1));
            Thread thread2 = new Thread(new ThreadStart(DisplayThread2));
            //Thread thread1 = new Thread(new ThreadStart(DisplayThread_1));
            //Thread thread2 = new Thread(new ThreadStart(DisplayThread_2));
            // start them
            thread1.Start();
            thread2.Start();
        }
    }
}

Enumerator (enum):
An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable. which is declared by using the enum keyword.
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum MachineState
{
    PowerOff = 0,
    Running = 5,
    Sleeping = 10,
    Hibernating = Sleeping + 5
}

Constant vs readonly:
Classes and structs can declare constants as members. 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.
Constants can be marked as public, private, protected, internal, or protected internal.
class Calendar
{
    const int months = 12;
    const int weeks = 52;
    const int days = 365;
    const double daysPerWeek = days / weeks;
    const double daysPerMonth = days / months;
}

Inheritance:
The process of deriving a new class(Derive Class) from an existing class(Base Class) is called as Inheritance. It helps reusability.
The new class—the derived class—then gains all the non-private data and behaviour of the base class in addition to any other data.
Struct do not support inheritance, but they can implement interfaces.
public class A
{
    public A() { }
}
public class B : A
{
    public B() { }
}

Static class:
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword.
They only contain static members. They cannot be instantiated. They are sealed. They cannot contain Instance Constructors (C# Programming Guide).
Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added.
the methods of the Math class in the System namespace.

Static member:
A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member.
Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called.
A non-static class can contain static methods, fields, properties, or events. Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.
public class Automobile
{
    public static int NumberOfWheels = 4;
    public static int SizeOfGasTank
    {
        get
        {
            return 15;
        }
    }
    public static void Drive() { }
    //other non-static fields and properties...
}

Generic collection:
A generic collection is strongly typed (type safe), meaning that you can only put one type of object into it. This eliminates type mismatches at runtime. Another benefit of type safety is that performance is better with value type objects because they don't incur overhead of being converted to and from type object.
Another very useful generic collection is the Dictionary, which works with key/value pairs. There is a non-generic collection, called a Hashtable that does the same thing, except that it operates on type object.
using System;
using System.Collections.Generic;
class Class1
{
    public class Customer
    {
        public Customer(int id, string name)
        {
            ID = id;
            Name = name;
        }
        private int m_id;
        public int ID
        {
            get { return m_id; }
            set { m_id = value; }
        }
        private string m_name;
        public string Name
        {
            get { return m_name; }
            set { m_name = value; }
        }
    }
    class Program
    {
        static void Main1(string[] args)
        {
            List<int> myInts = new List<int>();
            myInts.Add(1);
            myInts.Add(2);
            myInts.Add(3);
            for (int i = 0; i < myInts.Count; i++)
            {
                Console.WriteLine("MyInts: {0}", myInts[i]);
            }
            Dictionary<int, Customer> customers = new Dictionary<int, Customer>();
            Customer cust1 = new Customer(1, "Cust 1");
            Customer cust2 = new Customer(2, "Cust 2");
            Customer cust3 = new Customer(3, "Cust 3");
            customers.Add(cust1.ID, cust1);
            customers.Add(cust2.ID, cust2);
            customers.Add(cust3.ID, cust3);
            foreach (KeyValuePair<int, Customer> custKeyVal in customers)
            {
                Console.WriteLine("Customer ID: {0}, Name: {1}", custKeyVal.Key, custKeyVal.Value.Name);
            }
            Console.ReadKey();
        }
    }
}

Anonymous method:
Anonymous methods allow us to define a code block where a delegate object is acceptable. This facility saves us an extra step of creating a delegate for small code blocks that we want to pass to a delegate.
An anonymous method is a method without a name - which is why it is called anonymous. You don't declare anonymous methods like regular methods. Instead they get hooked up directly to events. You'll see a code example shortly.
An anonymous method is a method without any name. To understand better, a normal method is one which will have a name, return type optionally arguments and an access modifier. So, an anonymous method in C# 2.0 is a feature to have methods without name.
Anonymous methods can be used in the place where there is a use of a delegate.
using System;
using System.Collections.Generic;
class Class1
{
    [STAThread]
    static void Main(string[] args)
    {
        /// It also removes the cluttering of small methods in the class code.
        MyCollection objMyCol = new MyCollection();
        objMyCol.ItemList.Add("Aditya");
        objMyCol.ItemList.Add("Tanu");
        objMyCol.ItemList.Add("Manoj");
        objMyCol.ItemList.Add("Ahan");
        objMyCol.ItemList.Add("Hasi");
        // get an array of string items in the collection that start with letter 'A'
        string[] AStrings = objMyCol.GetFilteredItemArray(FilterStringWithA);
        Console.WriteLine("----- Strings starting with letter 'A' -----");
        foreach (string sa in AStrings)
        {
            Console.WriteLine(sa);
        }
        // get an array of string items in the collection that start with letter 'T'
        string[] TStrings = objMyCol.GetFilteredItemArray(FilterStringWithT);
        Console.WriteLine("----- Strings starting with letter 'T' -----");
        foreach (string sa in TStrings)
        {
            Console.WriteLine(sa);
        }
        //example 2
        AStrings = objMyCol.GetFilteredItemArray(delegate(string sItem)
        {
            if (sItem[0] == 'A')
                return true;
            else
                return false;
        });
        Console.WriteLine("----- Strings starting with letter 'A' -----");
        foreach (string sa in AStrings)
        {
            Console.WriteLine(sa);
        }
        // get an array of string items in the collection that start with letter 'T'
        TStrings = objMyCol.GetFilteredItemArray(delegate(string sItem)
        {
            if (sItem[0] == 'T')
                return true;
            else
                return false;
        });
        Console.WriteLine("----- Strings starting with letter 'T' -----");
        foreach (string sa in TStrings)
        {
            Console.WriteLine(sa);
        }
        Console.ReadLine();
    }
    public class MyCollection
    {
        public delegate bool SelectItem(string sItem);
        public string[] GetFilteredItemArray(SelectItem itemFilter)
        {
            List<string> sList = new List<string>();
            foreach (string sItem in m_sList)
            {
                if (itemFilter(sItem) == true) sList.Add(sItem);
            }
            return sList.ToArray();
        }
        public List<string> ItemList
        {
            get
            {
                return m_sList;
            }
        }
        private List<string> m_sList = new List<string>();
    }
    public static bool FilterStringWithA(string sItem)
    {
        if (sItem[0] == 'A')
            return true;
        else
            return false;
    }
    public static bool FilterStringWithT(string sItem)
    {
        if (sItem[0] == 'T')
            return true;
        else
            return false;
    }
}

Sealed Class:
Once a class is defined as sealed class, this class cannot be inherited. In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET, NotInheritable keyword serves the purpose of sealed. If you have ever noticed, structs are sealed. You cannot derive a class from a struct. 
using System;
class Class1
{
    static void Main(string[] args)
    {
        SealedClass sealedCls = new SealedClass();
        int total = sealedCls.Add(4, 5);
        Console.WriteLine("Total = " + total.ToString());
    }
}
// Sealed class
sealed class SealedClass
{
    public int Add(int x, int y)
    {
        return x + y;
    }
}

Data Abstraction & Encapsulation
1. Abstraction solves the problem in the design level
1. Encapsulation solves the problem in the implementation level
2. Abstraction is used for hiding the unwanted data and giving relevant data
2. Encapsulation means hiding the code and data in to a single unit to protect the data from outside world
3. Abstraction is a technique that helps to identify which specific information should be visible and which information should be hidden.
3. Encapsulation is the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible.


Property Vs Indexer:
Property
Indexer
Allows methods to be called as if they were public data members.
Allows elements of an internal collection of an object to be accessed by using array notation on the object itself.
Accessed through a simple name.
Accessed through an index.
Can be a static or an instance member.
Must be an instance member.
A get accessor of a property has no parameters.
A get accessor of an indexer has the same formal parameter list as the indexer.
A set accessor of a property contains the implicit value parameter.
A set accessor of an indexer has the same formal parameter list as the indexer, and also to the value parameter.
Supports shortened syntax with Auto-Implemented Properties (C# Programming Guide).
Does not support shortened syntax.

No comments:

Post a Comment