Questions tagged [init-only]
3 questions
14
votes
5 answers
In C#9, how do init-only properties differ from read-only properties?
I keep reading up on init-only properties in C#9 but I thought we already had that with read-only properties which can only be set in a constructor. After that, it’s immutable.
For instance, in the class here, both Name and Description can be…

Mark A. Donohoe
- 28,442
- 25
- 137
- 286
6
votes
2 answers
Setting init-only properties when using Activator.CreateInstance
C# 9.0 introduced init-only class properties feature but they can't be used when creating instances by class type with Activator.CreateInstance. A simplistic example:
class Person
{
public string Name { get; init; }
}
void Test()
{
Person…

Mikk L.
- 161
- 2
- 9
5
votes
2 answers
Should it be possible to set a C# init-only property at run time?
I tried writing some C# code to create an init-only property.
I was surprised to find that the property could be changed at run-time.
Have I misunderstood the idea of immutability?
I am using Visual Studio Community 16.9.3.
Sample code.
namespace…

Tony Stachnicki
- 51
- 2