Вопрос

I'd like an immutable class, or rather a class whose properties are initialised (whether they have public/private setters or not), in the constructor:

public class MyClass
{
    public string MyString { get; }

    public MyClass(string myString)
    {
        MyString = myString;
    }
}

Nice and simple, works fine. Is there any syntactic sugar here that will allow me to do this without the constructor based on the naming convention of my properties? Or am I waiting for C# 8's new 'record' feature?

I vaguely recall seeing something around auto property initialisers, but can't find how I'd tackle this using those.

Это было полезно?

Решение

At time of writing (July 2018), you need to wire up the ctor yourself in C#.

Лицензировано под: CC-BY-SA с атрибуция
scroll top