In C# we can now construct new objects using the curly brace constructor, i.e.
class Person {
readonly string FirstName {get; set;}
readonly string LastName {get; set;}
}
new Person { FirstName = "Bob", LastName = "smith" }
I need to construct this object using reflection, but if these member variables are marked readonly, I can only set them in the constructor, and there is only the curly-brace constructor available. Is there some way I can access the curly-brace-style constructor using reflection? Thanks.
First, properties cannot be marked read-only with the
readonly
keyword. They can only have non-public setter methods*).Second, there's no such thing as a “curly brace constructor”. It's just a syntactic sugar (a shortcut) for a set of statements like this:
Note that you could also use a constructor with parameters:
gets translated as:
Regarding reflection: To construct a new instance and initialize it in the same way as in the
new Person { FirstName = "Bob", LastName = "Smith" }
example you have to:Type.GetConstructor
) and call it or useActivator.CreateInstance
to instantiate the type,FirstName
property (seeType.GetProperty
),PropertyInfo.SetValue
),LastName
.*) Update: C# 9 will (as of May 2020) introduce init-only properties, which will be the equivalent of
readonly
fields, allowing property assignment during object initialization only (i.e. in the constructor or in an object initializer).This has no relation to constructor. This is simply short-handed syntax to initialize normal properties.
is exactly same as
And as people said. Your example wont compile. Because its not constructor.
How can you compile this? C# reports an error:
I'm guessing you mean private poperty setters instead of readonly properties (the get and set are shorthand for full getters and setters). Then you will have to do something like this to set the properties reflectively: