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.

2
  • This is part of C# 7. You can use it now with Visual Studio 2017 or JetBrains Rider. Jul 21, 2018 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? Jul 21, 2018 at 15:14

1 Answer 1

0

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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