public class MyClass
{
public string Name {get; KEYWORD set;}
public MyClass(string name)
{
this.Name = name;
}
}
Any ideas what the KEYWORD was? I searched all over but it's hard to find the get/set accessors in google.
public class MyClass
{
public string Name {get; KEYWORD set;}
public MyClass(string name)
{
this.Name = name;
}
}
Any ideas what the KEYWORD was? I searched all over but it's hard to find the get/set accessors in google.
The private
keyword allows the property to be set from anywhere within the class:
private set;
I.e:
public string Name {get; private set;}
If you also wanted to allow it to be set from an inheriting class, you could use protected
instead.
You could use the readonly
keyword to only allow the property to be set once, but it cannot be used on auto-implemented properties.
If you want to be able to set the value only in the constructor I would recommend you the readonly keyword:
public class MyClass
{
private readonly string _name;
public MyClass(string name)
{
_name = name;
}
public string Name
{
get { return _name; }
}
}
I know that using the READONLY keyword on a field let you write in this field once and it must be only in the constructor.
like GenericTypeTea said you are probably looking for the private keyword.
However, just to be clear, making your set accessors private doesn't restrict it to ONLY the constructor but anyway within the class.
To make the property ONLY settable from the constructor you want something like this
public class MyClass
{
private string name;
public string Name {get { return name;} }
public MyClass(string nameString)
{
name = nameString;
}
}