2

In C# I am creating properties in different ways.

Like this:

public Dimension X { get; set; }

and like this:

Dimension _x;
public Dimension X
{
    get { return _x; }
    set { _x = value; }
}

or even just using a public variable

public Dimension X;

What should I consider before using one over the other if I am "fairly" certain that the needs for getting and setting will not change often?

jth41
  • 3,808
  • 9
  • 59
  • 109

3 Answers3

1

Your first code is demonstrating Auto-implemented properties, a feature introduced with C# 3.0. It is same as your second approach where you have a backing field. (In case of auto implemented properties, compiler add the backing field)

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. (MSND)

Backing field is useful when you have some custom logic in get or set, but if you are not going to have any logic in your getter or setter then using auto implemented property would be fine.

Your last code is for a public field. It is different from public property. You can see this question Public Fields versus Automatic Properties for more details.

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
0

My recommendation is never to use the third option. Only expose properties through getters and setters in case you need to manipulate the values in the future.

Of the other two options, if you need to do manipulation of the value then a backing variable makes sense (your second option). If the property is a straight pass-thru of the value in and out then an "automatic" property (your first option) is short and concise but still gives you the option to have a backing variable in the future.

Craig W.
  • 17,838
  • 6
  • 49
  • 82
0

Basically you have to use

Dimension _x;
public Dimension X
{
    get { return _x; }
    set { _x = value; }
}

when you plan to add some extra actions like

Dimension _x;
public Dimension X
{
    get 
    {     
       // do more stuff here
       return _x; 
    }

    set 
    {
      // do more stuff here
       _x = value;     
    }
}
NoWar
  • 36,338
  • 80
  • 323
  • 498