Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I use Properties in C#?

Im not sure because in Java getter/setter are looking a little bit different but whats the "c# way" to code this stuff?

Option a.)

    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private int time;

    public int Time
    {
        get { return time; }
        set { time = value; }
    }

b.)

    private string _name;
    private int _time;

    public string name
    {
        get { return _name; }
        set { _name = value; }
    }

    public int time
    {
        get { return _time; }
        set { _time = value; }
    }

c.)

   public string name {get; set;}
   public int time {get; set;}

Ok there are some examples. What would look better? Should I write all the private variable declarations first then the properties or should I group my variable and property declaration next to each other.

like image 521
miri Avatar asked Jul 06 '12 13:07

miri


People also ask

What are the properties in C?

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they're public data members, but they're special methods called accessors.

Why do we need to use properties in C#?

Properties are used to restrict direct access to member variables of a class. Abstraction is maintained using properties. Whenever you want to instantiate an object and set data to it's member variables using property you can check some conditions whether the value will be set to the member variable or not.

Why do we use property?

Properties are special kind of class member, In Properties we use predefined Set or Get method. They use accessors through which we can read, written or change the values of the private fields. For example, let us Take a class named Employee, with private fields for name,age and Employee Id.


1 Answers

How about d, following .NET naming conventions:

public string Name { get; set; }
public int Time { get; set; } // Odd type for time, admittedly...

Don't bother writing the property manually yourself unless you do something non-trivial in it.

If you do write the property implementation manually, it's up to you how you name the private variable. Personally I'd use:

private string name;
public string Name
{
    get { /* whatever */ }
    set { /* whatever */ }
}

... but if you want to use underscores, that's your prerogative.

As for ordering of members - that's even more your own choice. Assuming you're working with a team, talk with the team and see what the local convention is.

like image 148
Jon Skeet Avatar answered Oct 19 '22 23:10

Jon Skeet