Posted by: Cirilo Meggiolaro | 12/25/2008

Tip of the day #72 – Class initializers

A nice feature from C# 3.0 is the ability to set object properties or fields during the object initialization.

Let’s assume we have a simple class named customer where we define some properties as demonstrated on the following code snippet:

public class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
}

Using the class initializer you may set the properties as the following code demonstrates:

Customer cust = new Customer
{
    ID = 1,
    Name = “Bill Smith”,
    DateOfBirth = new DateTime(1975, 05, 25)
};

You may use the initializers not only for properties but for fields as well. Since they are accessible you are able to access them.

Constructors

An important point is that the initializers don’t replace constructor parameters. On the first example you may realize that there are not constructors defined for the Customer class. It means that a parameterless constructor is used as default. If you define a parameterized constructor you’ll have to pass the parameters as the same way since you have started developing. The following code snippet demonstrates that:

public class Customer
{
    public Customer(int id, string name, DateTime dob)
    {
        this.ID = id;
        this.Name = name;
        this.DateOfBirth = dob;
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime DateOfBirth { get; set; }
    public decimal DiscountRate { get; set; }
}

You need to create an instance and pass the parameters as usual:

Customer cust = new Customer(1, “Bill Smith”, new DateTime(1975, 05, 25))
{
    DiscountRate = 5
};

Intellisense support

The intellisense is available and all accessible parameters and / or fields are listed as shown on the following picture:

Picture 1 - Intellisense support

Picture 1 - Intellisense support

Collections

Initializers may be used to add items to a collection.

List<int> customersID = new List<int>() {1, 2, 4, 7, 9, 10 };


Responses

  1. Am I forgeting something? The Name property is coming null…

    static void Main(string[] args)
    {
    Person person = new Person()
    {
    Id = 1,
    Name = “Fergara”,
    Birthday = DateTime.Now
    };

    Console.WriteLine(person.Name);
    Console.ReadKey(true);
    }

  2. The initializer code is ok. Please post the code for the Person class.


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

Categories

%d bloggers like this: