C# – Structure, Delegate and Interface

Standard

Structure

Structure same as class to encapsulate data and code but one major difference, its uses stack memory, and act as customized type. Can not inherit because structure is the value type. Initialize the variables inside the structure shows compiler error “cannot have instance field initializers in structs”. However variable ‘const‘ keyword able to initialize.

public struct structVsClass

{

//public int myStructFiled = 100; //compiler error : cannot have instance field initializers in structs

public const string strucField = " 1. Structure can not be inherited. Because, structure is the value type using stack memory. \r\n 2. structure field even with public modifier with ‘const’ keyword can not be accessed in instance, but accessible within the structure member. \r\n";

public string structProperty

{

get { return strucField; } set { value = strucField; }

}

}

Delegate

Delegate hold signature of the method, instantiate either named (method with same signature initialized with delegate instance) or anonymous (delegate instance directly initialized with anonymous method of same signature with ‘delegate‘ keyword) , type safe.

delegate int delegateSignature(int j, int i);

public class methodInSameSignature

{

public int multiplication(int j, int i)

{

return i * j;

}

public int add(int i, int j)

{

return i + j;

}

}

class Program

{

static void Main(string[] args)

{

methodInSameSignature mSS = new methodInSameSignature();

delegateSignature[] delegateInstance = {mSS.multiplication, mSS.add};

delegateSignature anonymouseDelegate = delegate(int i, int j)

{

return Math.Max(i,j);

};

foreach( delegateSignature ds in delegateInstance)

{

Console.WriteLine("Result of {0} is {1} .\r\n" , ds.Method.Name, ds(1, 1000).ToString());

}

Console.WriteLine("Result of {0} is {1} .\r\n" , anonymouseDelegate.Method.Name, anonymouseDelegate(999, 1000).ToString());

Console.ReadLine();

}

}

Interface

Interface also hold signature of the method, property, event and indexers , enable class designer. Can not instantiate directly it should implemented through class. Interface can be inherit from another inteface. Best example class with list value inherit using IEnumerable , IComparable

[SerializableAttribute]

public class List<T> : IList<T>, ICollection<T>,

IEnumerable<T>, IList, ICollection, IEnumerable

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s