C# 3.0 has some cool extensions based on 2.0. Let’s look at one of them, Object Initializing. In 2.0, we used to code either assigning values after instantiation or create custom initializers. Here’s a typical way we used to do:
public class Employee
{
private string _ID;
private string _FirstName;
private string _LastName;
public string ID
{
get { return _ID; }
set { _ID = value; }
}
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
public Employee() { }
public Employee(string id, string firstName, string lastName)
{
ID = id;
FirstName = firstName;
LastName = lastName;
}
}
public sealed class FullTimeEmployee : Employee
{
private decimal _WorkHours;
public decimal WorkHours
{
get { return _WorkHours; }
set { _WorkHours = value; }
}
public FullTimeEmployee() { }
public FullTimeEmployee(string id, string firstName, string lastName, decimal workhours)
: base(id, firstName, lastName)
{
WorkHours = workhours;
}
}
// Instantiation was done like this:
FullTimeEmployee ftEmployee = new FullTimeEmployee();
ftEmployee.ID = "101";
ftEmployee.FirstName = "John";
ftEmployee.LastName = "Doe";
ftEmployee.WorkHours = 40;
// Or with custom initializer
FullTimeEmployee ftEmployee = new FullTimeEmployee("101", "John", "Doe", 40);
//
//
In the 3.0 the whole thing can be simplified to (and you get the idea):
public class Employee
{
public string ID { get; set;}
public string FirstName { get; set;}
public string LastName { get; set;}
public Employee() { }
}
public sealed class FullTimeEmployee : Employee
{
public decimal WorkHours { get; set;}
public FullTimeEmployee() { }
}
// Instantiation can be done like this:
FullTimeEmployee ftEmployee =
new FullTimeEmployee() { ID = "101", FirstName = "John",
LastName = "Doe", WorkHours = 40 };
//
//
And same goes with collections too. It’s much simplified from initializing point of view.
Oh, did you check the C# ?? null coalescing operator? Its cool too. The ?? operator checks if the left side of the expression is null and if null then returns the right side of the expression.
Love coding!