0

Excuse me if my question is pretty much about code-style, but for simple cases which of the bellow is better?

CASE 1:

private static int number = 1;
public static int Number
{
    get { return number; }
    set { number = value; }
}

CASE 2:

public static int Number
{
    get;
    set;
}

I think case 2 is better because, when you have many properties in your class they won't consume so much space and the filesize will be reduced.

Johny P.
  • 648
  • 1
  • 9
  • 31
  • 1
    Why would you ask question that you know is not on-topic (otherwise what that "excuse me" for) and show no details about your research on the topic? At very least learning proper name of "automatic properties" would be nice touch. I'd recommend reading through results of serach - i.e. https://www.bing.com/search?q=C%23+-+properties+vs.+automatic+properties... – Alexei Levenkov Oct 04 '15 at 19:29
  • One small notice: In case A default value for `Number` is 1, while in case B it is 0 – nZeus Oct 04 '15 at 19:36
  • Yes, I initialized it to be 1 for the sake of the example. – Johny P. Oct 04 '15 at 19:37

2 Answers2

1

The syntax below is called auto properties, it doesn't matter in the terms of file size since in compilation time, a field is generated anyway (see, decompilation in the end of the answer) and there are get and set methods in the compilation results in both cases.

Auto properties allow you to keep your code more organized and short which is good for your code maintainability and readability, therefore you should prefer them when possible.

We will put aside the "In field without auto-property you can assign default value" topic for a second (also, it is possible now in auto-properties too in c# 6.0), sometimes, you want to run some more code inside the get or set methods of the property, like invoking event handles or validating the values, that's where standard property declaration comes into the picture, for example:

private int mNumber;

public int Number
{
    get
    {
        return Number;
    }
    set
    {
        if (Number == 8)
        {
            throw new CannotReceive8Exception();
        }
        else
        {
            mNumber = value;
        }
    }
}

If you look at the decompiled code of this code:

public int Number { get; set; }

You will see that the compiler has added a background private field anyway:

Fields

Tamir Vered
  • 10,187
  • 5
  • 45
  • 57
0

While there is no difference to the compiler, since it would generate the fields for you, I prefer to leave my code clean and just use

public int Num {get;set;}

in one line, since there is no supreme meaning to explicitly typing the code and keeping it in one line allows me to differentiate properties like this from methods, which span across multiple lines at glance.

Marian
  • 3,789
  • 2
  • 26
  • 36