Reputation: 10163
I am used in many cases to write a properties like
public string Data {get; private set; }
And usual I initialize them in the constructor How can I give the Data some value ,not explicitly using constructor
Upvotes: 1
Views: 399
Reputation: 1916
C# 9.0 will provide new init
accessor for this particular problem:
public class DataClass
{
public string Data {get; init; }
}
Now you can use object initializer for your DataClass
instead of constructor:
var d = new DataClass { Data = "newValue" };
More details here.
Upvotes: 0
Reputation: 223422
Instead of Auto-implemented property use a backing field , Initialize that field with same value and then expose it through property like:
private string _Data = "Some Value";
public string Data
{
get { return _Data; }
private set { _Data = value; } //or remove it
}
Upvotes: 7
Reputation: 2045
You could use a backing variable
private string _data = "foo";
public string Data {get {return _data;} private set {_data = value;}}
Or in C#6 you can write it like this
public string Data {get; private set; } = "foo";
Upvotes: 3
Reputation: 152644
Not with an automatic proeprty. If you have a backing field you can initialize it:
private string _Data = "some value";
public string Data {get {return _Data;} private set {_Data = value;} }
Upvotes: 1