It’s possible in C# to write things such way:
Instrument instr = new Instrument { ClassCode = "Hello", Ticker = "World" };
However to do that you have to add set; in the corresponding class:
class Instrument
{
public string ClassCode { get; set; }
public string Ticker { get; set; }
}
This means that later someone can accidentally change value:
instr.ClassCode.set = "Destroy"
And I don’t want to allow that. I.e., from one hand I want a readonly property, from another hand i want to create objects like that:
Instrument instr = new Instrument { ClassCode = "Hello", Ticker = "World" };
I’m not sure if this is possible. Probably I should use fields or something else instead of properties. I only want to have the syntax of the last sentence but keep things readonly at the same time.
upd: In short no, readonly properties are not allowed in any way. Regular constructor and “get” should be used in this case.
This happens because the code you’re using:
is just syntactic sugar for this:
The two samples above are exactly the same, the former is just shorthand for the latter.
What you want to achieve this functionality is to make these values private. Something like this:
What you have here are:
You’d instantiate it like this:
This means that you wouldn’t be able to use the syntactic sugar (object initializer, I think it’s called) to instantiate the class anymore, you’d have to use the constructor. So this would be a breaking change for the current implementation, but is a simple way to produce the desired functionality.