1

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.

  • This is part of C# 7. You can use it now with Visual Studio 2017 or JetBrains Rider. – Berin Loritsch Jul 21 '18 at 15:13
  • I thought it was removed from the feature list? I think you're right in that it was originally on there. Unless by 'use IT' you mean the syntax I've posted? – JᴀʏMᴇᴇ Jul 21 '18 at 15:14
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.