Labels

Thursday, September 17, 2009

Automatic Properties - Where the fun stops

Using Accessibility Modifiers on Auto Properties

 

This post could be older for you. Below is the way to define properties.

 

public class Person

{

    private string firstName;

    public string FirstName

    {

        get { return firstName; }

        set { firstName = value; }

    }

}

 

You get to write the same in C#3.0 as below.

 

public class Person

{

    public string FirstName { get; set; }

}

 

Unfortunately, for most developers, the above use of automatic properties is where the fun stops. Once they get to the point where they need to have a read-only property, they fall back to their old tricks and write this:

 

public class Person

{

    private string firstName;

    public string FirstName

    {

        get { return firstName; }           

    }

}

 

You don’t need to do that silly way. You just need to do this:

 

public class Person

{       

    public string FirstName { get; private set; }

}

 

public class Person

{       

    public string FirstName { private get; set; }

}

 

public class Person

{       

    public string FirstName { get; protected set; }

    public string LastName { get; internal set; }

}

 

 

Hope this helps.

 

Thanks & Regards,

Arun Manglick || Senior Tech Lead

 

 

No comments:

Post a Comment