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;
}
}
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
Either add a private setter to your property:
public string Colour{ get; private set;}
Or add a readonly backing-field:
private string _colour;
public string Colour{ get return this._colour; }
public Apple(string colour)
{
this._colour = colour;
}
I think what you're looking for is this, which keeps your internal variable protected by only exposing a GET to the outside world. For extra safety you could mark _colour as readonly so that it can't be changed within the class itself either (after instantiation), but I think that's overkill. What if your apple gets old and needs to turn brown ?!
class Program
{
static void Main(string[] args)
{
Apple a = new Apple("green");
}
}
class Apple
{
private string _colour;
public string Colour
{
get
{
return _colour;
}
}
public Apple(string colour)
{
this._colour = colour;
}
}
You have a couple of options here:
// Make the string read only after the constructor has set it
private readonly string colour
public string Colour { get { return colour; } }
public Apple(string colour)
{
this.colour = colour;
}
// Make the string only readonly from outside but editing from within the class
public string Colour { get; private set; }
public Apple(string colour)
{
this.Colour= colour;
}