Saturday, April 13, 2013

object initializer in c sharp

In this post  i would like to give an example on object initializers in c#.net.
1.Object initializers are used to initialize the instance variables automatically
2.These are bit similar to constructions syntaxically
obs:
if the class name is test
Test t=new test(101,"bhaskar") is called as constructor
Test t=new test{eno=101,ename="bhaskar"} is called as object initializers
In the above syntax eno and ename are two implemented properties
3.The main objective of object initializer is to save no of lines  in the source code

Example:
place a button on the form
Cod in GD
class emp
{
public int eno {set;get}
public int sal {set;get}
public string name {set;get}
}
Code for button click event
{
emp e1= new emp{eno=101,ename="bhaskar",sal=5000};
MessageBox.Show(e1.no+""+e1.name+""+e1.sal);

No comments:

Bel