Frage

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

War es hilfreich?

Lösung

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
}

Andere Tipps

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";

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;} }

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top