Maxime Joyal Maxime Joyal - 3 months ago 11
C# Question

How to initialise object with private setters?

When I use the following:

static public string myString { get; private set; }


How can I set value at the same time? Problem is my class is static, so right at it's declaration, I need to make sure it has a value.

Normally I use it with non static class, so I set the value in the class constructors.

Answer

You cannot do it prior to C# 6.0, but C# 6.0 adds this syntax:

static public string myString { get; private set; } = "Hello";

Unless you plan to set myString at some later time in your program, consider making the property read-only (that's another new feature of C# 6.0):

static public string myString { get; } = "Hello";
Comments