Home
Gallery
GuestBook
SourceCode
Contact

Automatic Properties and Object Initializers

Posted in C#
This post has been read 947 times

Automatic Properties

In this post we will look at some of the new features added in C# 3.0. The first of these will be automatic properties. Automatic properties gives us with a shorthand notation for defining a new property.


    1 public class AutoProp

    2 {

    3     public string AddedBy { get; set; }

    4     public DateTime AddedDate { get; set; }

    5 

    6     public int ViewCount { get; private set; }

    7 

    8     //Normal way of defining property

    9     private int id;

   10     public int Id

   11     {

   12         get { return id; }

   13         set { id = value; }

   14     }

   15 }

Notice that the first 2 properties do not have Getters or Setters, what is happing is that the C# compiler generates the getters and setters automatically. Also notice that the fields are declared as public unlike the private field id. The ViewCount field in the snippet is interesting, because it has a private set. What this means is that you cant directly assign a value to this field from an object of the class. Thing to note in automatic properties are that you cant add any logic for an automatic property and also you cant create read-only automatic properties.

Object Initializers

Object initializers allows us to initialize the properties of an object while its being created.

    1 public class Product

    2 {

    3     public int Id { get; set; }

    4     public string Name { get; set; }

    5 }

    6 

    7 public class ObjectInit

    8 {

    9     public void SetProduct()

   10     {

   11         //Normal way

   12         Product prod = new Product();

   13         prod.Id = 1;

   14         prod.Name = "Product1";

   15 

   16         //New way

   17         Product newProd = new Product() { Id = 2, Name = "Product2" };

   18     }

   19 }

For eg. in the above snippet, the Product class has 2 properties Id and Name. In the ObjectInit class, i am creating 2 objects of the Product class viz. prod and newProd. The new Prod is initialized directly when the object is created unlike the prod where first the object is created and then the properties are initialized.

I will continue on other new features in my next post





Name:
E-mail:
Website:
Comment:
 
Anti Bot Image:

Insert Cancel


Subscribe

Random Photo

My Tweets


Top Posts

Source Code

The source code to this site is open-source. You can download the code from here.

Categories


Recent Blogs


Archives


Blogroll