Thursday, 26 July 2012

Inheritance in C#


class Animal
{
    public Animal()
    {
        Console.WriteLine("Animal constructor");
    }
    public void Greet()
    {
        Console.WriteLine("Animal says Hello");
    }
    public void Talk()
    {
        Console.WriteLine("Animal talk");
    }
    public virtual void Sing()
    {
        Console.WriteLine("Animal song");
    }
};

class Dog : Animal
{
    public Dog()
    {
        Console.WriteLine("Dog constructor");
    }
    public new void Talk()
    {
        Console.WriteLine("Dog talk");
    }
    public override void Sing()
    {
        Console.WriteLine("Dog song");
    }
};

Animal a1 = new Animal();
a1.Talk();
a1.Sing();
a1.Greet();



Dog d1 = new Dog();
d1.Talk();
d1.Sing();
d1.Greet();



class Color
{
    public virtual void Fill()
    {
        Console.WriteLine("Fill me up with color");
    }
    public void Fill(string s)
    {
        Console.WriteLine("Fill me up with {0}",s);
    }
};

Color c1 = new Color();
c1.Fill();
c1.Fill("red");


class Green : Color
{
    public override void Fill()
    {
        Console.WriteLine("Fill me up with green");
    }
};


Green g1 = new Green();
g1.Fill();
g1.Fill("violet");

//Output
Fill me up with green
Fill me up with violet


class Software
{
    public Software()
    {
        m_x = 100;
    }
    public Software(int y)
    {
        m_x = y;
    }
    protected int m_x;
};

class MicrosoftSoftware : Software
{
    public MicrosoftSoftware()
    {
        Console.WriteLine(m_x);
    }
};


MicrosoftSoftware m1 = new MicrosoftSoftware();



class DundasSoftware : Software
{
     
    public DundasSoftware(int y) : base(y)
    {
        Console.WriteLine(m_x);
    }
   
    //Here we are telling the compiler to first
    //call the other overload of the constructor
    public DundasSoftware(string s, int f) : this(f)
    {
        Console.WriteLine(s);
    }
};


Anonymous Methods In C#


Anonymous Methods In C#

A block of code can be included while a delegate is defined. This defined block is called anonymous method. With this approach, there is no need to create a method.
Example
using System;
namespace ConsoleApplication3
{
public delegate int Calculate(int num);
class Factorial
{
static void Main(string[] args)
{
int value = 6;
Calculate objFact = delegate(int number)
{
int num = 1;
for (int i = 1; i <= number; i++) { num *= i; } return num; }; Console.WriteLine("Factorial : " + objFact(value)); } } }


Anonymous Methods declared in some user defined method


using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
public delegate int Calculate(int num);
class Factorial
{
static void Start()
{
int value = 5;
Calculate objFact = delegate(int number)
{
int num = 1;
for (int i = 1; i <= number; i++) { num *= i; } return num; }; Console.WriteLine("Factorial : " + objFact(value)); } static void Main(string[] args) { Start(); } } }


Anonymous Methods without return types


using System;
namespace ConsoleApplication3
{
public delegate void Calculate(int num);
class Factorial
{
static void Main(string[] args)
{
Calculate objFact = delegate(int number)
{
int num = 1;
for (int i = 1; i <= number; i++) { num *= i; } Console.WriteLine("Factorial: " + num); }; int value; Console.Write("Num: "); value = Int32.Parse(Console.ReadLine()); objFact(value); } } }


Anonymous Methods without return types and arguments


using System;
namespace ConsoleApplication3
{
public delegate void Calculate();
class Factorial
{
static void Main(string[] args)
{
Calculate objFact = delegate()
{
int num = 1;
Console.Write("Num:");
int number = Int32.Parse(Console.ReadLine());
for (int i = 1; i <= number; i++) { num *= i; } Console.WriteLine("Factorial: " + num); }; objFact(); } } } Example
using System;
namespace ConsoleApplication3
{
public delegate int Calculate(int num);
class Factorial
{
static void Start(int n)
{
int value = n;
Calculate objFact = delegate(int number)
{
int num = 1;
for (int i = 1; i <= number; i++) { num *= i; } return num; }; Console.WriteLine("Factorial : " + objFact(value)); } static void Main(string[] args) { int value; value = Int32.Parse(Console.ReadLine()); Start(value); } } }


Passing Paramenters to Anonymous Methods


using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
public delegate void Add(out int numOne, out int numTwo);
class Maths
{
static void Start()
{
int valOne;
int valTwo;
Add objAddition = delegate(out int numOne, out int numTwo)
{
numOne = 10;
numTwo = 20;
int result = numOne + numTwo;
Console.WriteLine("Result of Addition : " + result);
};
objAddition(out valOne, out valTwo);
}
static void Main(string[] args)
{
Start();
}
}
}
Not more than one value can be passed in anonymous delegate. If you want to pass more than one value then you will have to use out keyword.

Anonymous method returning a value and without any arguments


using System;
namespace ConsoleApplication3
{
public delegate void Calculate();
class Factorial
{
static void Start(int n1,int n2)
{
int value1 = n1;
int value2 = n2;
Calculate objFact = delegate()
{
int result = value1 + value2;
Console.WriteLine(result);
};
objFact();
}
static void Main(string[] args)
{
int value1,value2;
value1 = Int32.Parse(Console.ReadLine());
value2 = Int32.Parse(Console.ReadLine());
Start(value1,value2);
}
}
}


Events In C Sharp


Events In C#

Events are nothing but situations at which the message is sent to an object to signal the occurrence of the action. These actions can be caused by the user interaction or within the object itself.
Events are declared using delegates. Delegate object encapsulates a method so that it can be called anonymously. An event is a way for a class to allow clients to give it delegates to methods that should be called when the event occurs. When the event occurs, the delegate(s) given to it by its clients are invoked. Example 1:
using System;
public delegate void CustomerDetails();
class Bank
{
string _custName;
int _custID;
event CustomerDetails Customer;
public Bank()
{
_custID = 1001;
_custName = "Patrick";
}
void ShowCustomerDetails()
{
Console.WriteLine("Customer ID : " + _custID);
Console.WriteLine("Customer Name : " + _custName);
}
static void Main(string [] args)
{
Bank objBank = new Bank();
objBank.Customer += new CustomerDetails(objBank.ShowCustomerDetails);
objBank.Customer();
}
}


Custom Events


using System;
public delegate void CustomerDetails();
public delegate void AccountDetails();
class Bank
{
string _custName;
String _accountType;
int _custID, _accountNumber;
event CustomerDetails Customer;
event AccountDetails Account;
public Bank()
{
_custID = 1001;
_accountNumber = 10;
_accountType = "Fixed";
_custName = "Patrick";
}
void ShowCustomerDetails()
{
Console.WriteLine("Customer ID : " + _custID);
Console.WriteLine("Customer Name : " + _custName);
}
void ShowAccountDetails()
{
Console.WriteLine("Account Number: " + _accountNumber);
Console.WriteLine("Account Type: " + _accountType);
}
static void Main(string [] args)
{
Bank objBank = new Bank();
objBank.Customer += new CustomerDetails(objBank.ShowCustomerDetails);
objBank.Account += new AccountDetails(objBank.ShowAccountDetails);
objBank.Customer();
objBank.Account();
}
}

Events and Inheritance


using System;
public delegate void Display(string msg);
public class Parent
{
event Display Print;
protected void InvokeMethod()
{
Print += new Display(PrintMessage);
Check();
}
void Check()
{
if (Print != null)
{
PrintMessage("Welcome to C#");
}
}
void PrintMessage(string msg)
{
Console.WriteLine(msg);
}
}
class Child : Parent
{
static void Main(string[] args)
{
Child objChild = new Child();
objChild.InvokeMethod();
}
}

Using abstract and sealed Events


using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
public delegate void Show();
abstract class AbstractEvents
{
abstract protected event Show Display;
abstract protected void SetDetails(string valueOne, int valueTwo);
}
class Employee : AbstractEvents
{
protected override event Show Display;
int _empID;
string _empName;
protected override void SetDetails(string valueOne, int valueTwo)
{
_empID = valueTwo;
_empName = valueOne;
}
void GetDetails()
{
Console.WriteLine("Employee ID: " + _empID);
Console.WriteLine("Employee Name: " + _empName);
}
static void Main(string[] args)
{
Employee objEmp = new Employee();
objEmp.SetDetails("John", 101);
objEmp.Display += new Show(objEmp.GetDetails);
objEmp.Display();
}
}
}

Sealed events cannot be inherited


using System;
public delegate void GetInfo();
class Employee
{
int _empID = 10;
string _empName = "James" ;
protected virtual event GetInfo ShowDetails;
void GetDetails()
{
Console.WriteLine("Employee ID: " + _empID);
Console.WriteLine("Employee Name: " + _empName);
}
public void Invoke()
{
ShowDetails += new GetInfo(GetDetails);
ShowDetails();
}
}
class Department : Employee
{
string _departmentName = "Accounts";
protected sealed override event GetInfo ShowDetails;
void Display()
{
Console.WriteLine("Department Name: " + _departmentName);
}
public void NewInvoke()
{
ShowDetails += new GetInfo(Display);
ShowDetails();
}
}
class Salary : Department
{ //protected override event GetInfo ShowDetails;
void Show() {}
static void Main(string [] args)
{
Salary objSalary = new Salary();
objSalary.ShowDetails += new GetInfo(objSalary.Show);
objSalary.Invoke();
objSalary.NewInvoke();
}
}


Abstract Classes In C#


Abstract Classes In C#

Abstract classes are one of the essential behaviors provided by .NET. Abstract classes are created if you want to make classes that only represent base classes, and don’t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'.
So an abstract class means that, no object of this class can be instantiated, but can make derivations of this. The abstract keyword enables you to create classes and class members solely for the purpose of inheritance—to define features of derived, non-abstract classes.
Example:
abstract class absClass1
{
public abstract int AddTwoNumbers(int Num1, int Num2);
public void PrintNumbers()
{
int res = 10;
Console.WriteLine("Result: "+ res);
}
}
class absClass2 : absClass1
{
public override int AddTwoNumbers(int Num1, int Num2)
{
return Num1 + Num2;
}
public static void Main()
{
absClass2 cls2 = new absClass2();
Console.WriteLine(cls2.AddTwoNumbers(30, 30));
cls2.PrintNumbers();V }
}

Structures In C Sharp


Structures in C#

A structure allows you to create your own custom data types and it contains one or more members that can be of different data types. It can contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types . Structures are very similar to classes but there are some restrictions present in the case of structures that are absent in the case of classes.
For example you cannot initialize structure members. Also you cannot inherit a structure whereas classes can be inherited. Another important feature of structures differentiating it from classes is that a structure can't have a default parameter-less constructor or a destructor. A structure is created on the stack and dies when you reach the closing brace in C# or the End structure in VB.NET.
But one of the most important differences between structures and classes is that structures are referenced by value and classes by reference. As a value type, allocated on the stack, structs provide a significant opportunity to increase program efficiency. Objects on the stack are faster to allocate and de-allocate. A struct is a good choice for data-bound objects, which don’t require too much memory. The memory requirements should be considered based on the fact that the size of memory available on the stack is limited than the memory available on the heap. Thus we must use classes in situations where large objects with lots of logic are required.

struct initialized using both default and parameterized constructors


using System;
public struct Point
{
public int x, y;
public Point(int p1, int p2)
{
x = p1;
y = p2;
}
}

class MainClass {
public static void Main()
{
Point myPoint = new Point();
Point yourPoint = new Point(10,10);
Console.Write("My Point: ");
Console.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y);
Console.Write("Your Point: ");
Console.WriteLine("x = {0}, y = {1}", yourPoint.x, yourPoint.y);
}
}

struct initialized without using new operator


public struct Point
{
public int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
class MainClass
{
public static void Main()
{
Point myPoint;
myPoint.x = 10;
myPoint.y = 20;
Console.WriteLine("My Point:");
Console.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y);
}
}



Delegates in C#


Delegates in C#

A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value.

Steps Required To Implement Delegate


  • Defining Delegates
    The foremost step is to define the delegate. The definition of the delegate specifies the method signature, return type of the method, access modifier and the delegate name. The method signature specifies the order and type of each argument. The definition of a delegate is indicated by the usage of the delegate keyword. As shown in the above code segment, the delegate name is calculation, it's access modifier is public, it receives two integer arguments and returns an integer value.
  • Creating Delegate Method Handler(s)
    The next step is to define the method(s) that will be associated with the delegate. In the above code segment, a method named add is defined. This method must have same method signature as that of the delegate, as shown in the above code segment.
  • Hooking up Delegates and Method Handlers
    For a delegate method handler to be invoked, it must be assigned to a delegate object. In the above code, the delegate object is calc_delegate and is hooked up to the method handler add.
  • Invoking the method through the Delegate
    The last step is to invoke the methods that are associated with the delegate. A delegate method handler is invoked by making a method call on the delegate itself. This causes the method handler to invoke with the assigned input parameters as if they were invoked directly by the program, as shown in the above code.

Simple Delegate


using System;
public delegate void delprt();
class dummy
{
public void prt()
{
System.Console.WriteLine("Eat");
}
public static void Main()
{
dummy obj = new dummy();
delprt delVal = new delprt(obj.prt);
delVal();
}
}

Delegate Referencing More Than One Methods


using System;
public delegate void delprt();
class dummy
{
public void prt()
{
System.Console.WriteLine("Eat");
}
public void display()
{
Console.WriteLine("this is the display function");
}
public static void Main()
{
dummy obj = new dummy();
delprt delVal = new delprt(obj.prt);
delVal += new delprt(obj.display);
delVal();
}
}

Delegate With Arguments


Example 1: using System;
public delegate void delFunction(int num);
class dummy
{
int val;
void prt(int num)
{
val = num;
System.Console.WriteLine(val);
}
public static void Main()
{
dummy obj= new dummy();
delFunction dd = new delFunction(obj.prt);
dd(44);
}
}

Example 2:
using System;
public delegate void delFunction(int num);
class dummy
{
static int val;
public static void prt(int num)
{
val = num;
System.Console.WriteLine(val);
}
public static void Main()
{
delFunction dd = new delFunction(prt);
dd(44);
}
}

Example 3:
using System;
public delegate int delFunction(int num);
class dummy
{
int val;
int prt(int num)
{
val = num;
return val;
}
public static void Main()
{
dummy obj= new dummy();
delFunction dd = new delFunction(obj.prt);
System.Console.WriteLine(dd(44));
}
}

Multiple Delegates

using System;
public delegate double CalculateArea(double val);
public delegate double CalculateVolume(double val);
class Cube
{
static double Area(double val)
{
return (val * val);
}
static double Volume(double val)
{
return (val * val * val);
}
static void Main(string[] args)
{
CalculateArea objArea = new CalculateArea(Area);
CalculateVolume objVol = new CalculateVolume(Volume);
Console.WriteLine("Surface area of Cube: " + objArea(20));
Console.WriteLine("Volume of Cube: " + objVol(20));
}
}

Multicast Delegate

using System;
public delegate void Maths (int valOne, int valTwo);
class MathDemo
{
static void Addtion (int valOne, int valTwo)
{
int result= valOne + valTwo;
Console.WriteLine("Addition: " + valOne + " + " + valTwo + " = " + result);
}
static void Subtraction (int valOne, int valTwo)
{
int result = valOne - valTwo;
Console.WriteLine ("Subtraction: "+valOne +" - " +valTwo+ " = " + result);
}
static void Multiplication (int valOne, int valTwo)
{
int result = valOne * valTwo;
Console.WriteLine ("Multiplication: "+valOne +" * " +valTwo+ " = " + result);
}
static void Division (int valOne, int valTwo)
{
int result = valOne / valTwo;
Console.WriteLine ("Division: "+valOne +" / " +valTwo+ " = " + result);
}
static void Main(string [] args) v {
Maths objMaths = new Maths(Addtion);
objMaths += new Maths(Subtraction);
objMaths += new Maths(Multiplication);
objMaths += new Maths(Division);
if (objMaths != null)
{
objMaths(20,10);
}
}
}

Exceptions in Multicast Delegates


using System;
delegate void DelSeries();
class Numbers
{
void Fibonacci()
{
int i = 0, j = 1;
Console.WriteLine("Fibonacci Series of 10 numbers: " + i + " and " + j);
for (int k = 0; k < 10; k++) { int c = i + j; Console.Write(" " + c); i = j; j = c; } Console.WriteLine(); } void Factorial() { int fact = 1; for (int i = 1; i <= 5; i++) { fact *= i; } Console.WriteLine("Factorial of 5: " + fact); } static void Main(string[] args) { Numbers objNum = new Numbers(); DelSeries objSeries = new DelSeries(objNum.Fibonacci); objSeries += new DelSeries(objNum.Factorial); if (objSeries != null) { foreach (Delegate d in objSeries.GetInvocationList()) { try { d.Method.Invoke(objNum, null); } catch (Exception objExcep) { Console.WriteLine("Error: " + objExcep); } } } else { return; } } }


System.Delegate Class


using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
public delegate void Messenger(int value);
class CompositeDelegates
{
static void EvenNumbers(int value)
{
Console.Write("Even Numbers: ");
for (int i = 2; i <= value; i += 2) { Console.Write(i + " "); } } void OddNumbers(int value) { Console.WriteLine(); Console.Write("Odd Numbers: "); for (int i = 1; i <= value; i += 2) { Console.Write(i + " "); } } static void Start(int number) { CompositeDelegates objComposite = new CompositeDelegates(); Messenger objDisplayOne = new Messenger(EvenNumbers); Messenger objDisplayTwo = new Messenger(objComposite.OddNumbers); Messenger objDisplayComposite = (Messenger)Delegate.Combine(objDisplayOne, objDisplayTwo); objDisplayComposite(number); Console.WriteLine(); Object obj = objDisplayComposite.Method.ToString(); if (obj != null) { Console.WriteLine("The delegate invokes an instance method: " + obj); } else { Console.WriteLine("The delegate invokes only static methods"); } } static void Main(string[] args) { int value = 0; Console.WriteLine("Enter the values till which you want to display even and odd numbers"); try { value = Convert.ToInt32(Console.ReadLine()); } catch (FormatException objFormat) { Console.WriteLine("Error: " + objFormat); } Start(value); } } }


Covariance and Contravariance in Delegates


Covariance and contravariance provide a degree of flexibility when matching method signatures with delegate types.
Covariance permits a method to have a more derived return type than what is defined in the delegate.
Contravariance permits a method with parameter types that are less derived than in the delegate type.
Covariance
using System;
class Shape { }
class Triangle : Shape
{
public delegate Shape Display();
public static Shape ShapeInfo() { }
public static Triangle TriangleInfo() { }
static void Main(string[] args)
{
Display objDispOne = ShapeInfo;
Display objDispTwo = TriangleInfo;
}
}
Contravariance
using System;
class Shape { }
class Triangle : Shape
{
public delegate void Display(Triangle objTriangle);
static Shape ShapeInfo(Shape objShape) { }
static void TriangleInfo(Triangle objTriangle) { }
static void Main(string[] args)
{
Display objDispOne = ShapeInfo;
Display objDispTwo = TriangleInfo;
}
}

The delegates are used as a reference to the methods


using System;
public delegate void Set(int num, string arg);
public delegate void Get();
class Employee
{
string _empName;
int _empID;
void SetDetails(int empNo, string name)
{
_empName = name;
_empID = empNo;
}
void GetDetails()
{
Console.WriteLine("Employee Name: " + _empName);
Console.WriteLine("Employee ID: " + _empID);
}
static void Main(string[] args)
{
Employee objEmp = new Employee();
Set objSet = new Set(objEmp.SetDetails);
Get objGet = new Get(objEmp.GetDetails);
objSet(20, "John");
objGet();
}
}


Enumerations in C#


Enumerations in C#

Enumerations are types that inherit from System.Enum. The elements of an enumeration are expressed in words rather than numbers, which makes it convenient for understanding the meaning of the value being used. Enumerations symbolically represent a set of values of one of the primitive integral types. The type of the elements of an enumeration can be byte, short, int or long. If no type is specified explicitly, the default type is int.
public enum Categories
{
Burgers = 1,
Desserts = 2,
DrinkXSpecials = 3,
FromXtheXGrills = 4,
HappyXHour = 5,
KidsXMenu = 6,
LunchXSpecials = 7,
PartyXMenu = 8,
Salads = 9,
Sandwiches = 10,
Seafood_XPastasXandXmore = 11,
Soups = 12,
}
public class UserEnum
{
public static void Main()
{
int c1 = (int)Categories.Burgers;
int c2 = (int)Categories.KidsXMenu;
Console.WriteLine(c1 + " " + c2 );
}
}


Boxing-UnBoxing in C#


Boxing - Unboxing in C#

Boxing and unboxing is a essential concept in .NET’s type system. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object. Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object.
Converting a value type to reference type is called Boxing. Unboxing is the opposite operation and is an explicit operation.
public class Square
{
public static void main()
{
int i = 1;
object o = i;
int j = (int)o;
}
}