2

My first time posting! Long time lurker.

I'm creating a static class, and this answer was very helpful: C# - Winforms - Global Variables

Here's the code from that answer for clarity:

static class Global
  {
    private static string _globalVar = "";

    public static string GlobalVar
    {
        get { return _globalVar; }
        set { _globalVar = value; }
    }
  }

However, in the process, ReSharper has recommended the code changes to this:

public static string value1 { get; set; } = "";

public static string value2 { get; set; } = "";

I don't think there's any difference, but I want to be 100% certain.

So my question is, is there any difference between the two, and if so, which one is the most desirable?

1 Answers1

2

That's "syntactic sugar". The version

public static string value1 {get;set;} = "";

compiles almost exaclty the way the previous explicit version

private static string _value1 = "";
public static string value1 {
    get { return _value1; }
    set { _value1 = value; }
}

would compile. The compiler creates the backing field for you and initializes it.

So if you don't need to do special things in the getter or setter method, I'd prefer the shorter version (the so called auto-property), because there is less boiler-plate code.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
  • Cool, I thought it was just boiler-plate tidy, but wanted to double check it didn't affect the functionality in any way that I was glossing over! Thank you. Will mark as answer as soon as I can. – PoweredByDoritos Oct 04 '18 at 11:20