Hi Friends...
C# 3.0 (LINQ) has got some nice features and Object Initializers is one of it. Here, I am going to describe what is it and where can it be useful to us.
I have a class called Employee like this :
public class Employee
{
string name;
string city;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
}
Now I want to initialize properties of this class. So, I can have something like this :
class Program
{
static void Main(string[] args)
{
//Traditional way
Employee emp = new Employee();
emp.Name = "XXX";
emp.City = "YYY";
}
}
Here, It will initialize City and Name properties of emp object. With C# 3.0, I can directly initialize the properties at time of object initialization itself. I can have something like this :
class Program
{
static void Main(string[] args)
{
// Using Object Initializers
Employee emp = new Employee {Name = "XXX", City="YYY" };
}
}
You can see, how easy it is to initialize the object in C# 3.0 . And good thing is it provides intelisense window for properties of that class. I need not to write extra code in order initialize object. This is a one of the good feature of C# 3.0 .
C# 3.0 (LINQ) has got some nice features and Object Initializers is one of it. Here, I am going to describe what is it and where can it be useful to us.
I have a class called Employee like this :
public class Employee
{
string name;
string city;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
}
Now I want to initialize properties of this class. So, I can have something like this :
class Program
{
static void Main(string[] args)
{
//Traditional way
Employee emp = new Employee();
emp.Name = "XXX";
emp.City = "YYY";
}
}
Here, It will initialize City and Name properties of emp object. With C# 3.0, I can directly initialize the properties at time of object initialization itself. I can have something like this :
class Program
{
static void Main(string[] args)
{
// Using Object Initializers
Employee emp = new Employee {Name = "XXX", City="YYY" };
}
}
You can see, how easy it is to initialize the object in C# 3.0 . And good thing is it provides intelisense window for properties of that class. I need not to write extra code in order initialize object. This is a one of the good feature of C# 3.0 .
No comments:
Post a Comment