Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing read-only properties with { get; }

Why doesn't this run:

  class Program
  {
    static void Main(string[] args)
    {
      Apple a = new Apple("green");
    }
  }

  class Apple
  {

    public string Colour{ get; }

    public Apple(string colour)
    {
      this.Colour = colour;
    }

  }
like image 947
whytheq Avatar asked Dec 05 '22 03:12

whytheq


1 Answers

Your code is valid for C# 6, which comes with Visual Studio 2015. It is not valid for previous versions of the language or Visual Studio. Technically, you can install an old pre-release version of Roslyn in VS 2013 but it isn't worth the trouble now that VS 2015 was released.

For this problem to occur, either you are using the wrong version of Visual Studio to compile C# 6 code, or you are trying to compile your code from the command line using the wrong development environment -ie, your PATH points to the old compiler. Perhaps you opened the 'Developer Command Prompt for 2013' instead of 2015?

You should either compile your code using Visual Studio 2015, or ensure your path variable points to the latest compiler.

If you have to use Visual Studio 2013 or older, you'll have to change your code to use the older syntax, eg:

public readonly string _colour;

public string Colour { get {return _colour;}}

public Apple(string colour)
{
    _colour=colour;
}

or

public string Colour {get; private set;}

public Apple(string colour)
{
    Colour=colour;
}

Note that the second option isn't truly read-only, other members of the class can still modify the property

NOTE

You can use Visual Studio 2015 to target .NET 4.5. The language and the runtime are two different things. The real requirement is that the compiler must match the language version

like image 89
Panagiotis Kanavos Avatar answered Dec 23 '22 01:12

Panagiotis Kanavos