Search code examples
c#methodsparentheses

Are parentheses mandatory to include in C# methods?


I have seen multiple tutorials that show C# method creation with parentheses containing parameters or simple empty. I have also seen a C# method written with out parentheses.

public int Value {
    get{ return _Value; }
    set{ _Value = value; }
}

I haven't tested out that code but is this allowed? Is it considered bad form?


Solution

  • As in Philip's answer, your example code is actually a Property,

    But you perhaps have hit on something that many actually miss and that is that Properties are implemented using one or two methods. They get created for you by the compiler and contain the contents of each of the get and/or set blocks.

    So, a property of:

    public string Name {
      get {
        return "Fred";
      }
    }
    

    Is a nicer way of writing:

    public string GetName() {
      return "Fred";
    }