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.
<< is the left shift operator. It is shifting the number 1 to the left 0 bits, which is equivalent to the number 1 .
%d is a format specifier, used in C Language. Now a format specifier is indicated by a % (percentage symbol) before the letter describing it. In simple words, a format specifier tells us the type of data to store and print. Now, %d represents the signed decimal integer.
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:
Person p = new Person(); // standard parameterless constructor is called
p.FirstName = "Bob";
p.LastName = "Smith";
Note that you could also use a constructor with parameters:
new Person(1, 2, 3) { FirstName = "Bob", LastName = "Smith" }
gets translated as:
Person p = new Person(1, 2, 3);
p.FirstName = "Bob";
p.LastName = "Smith";
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 use Activator.CreateInstance
to instantiate the type,FirstName
property (see Type.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.
new Person { FirstName = "Bob", LastName = "smith" };
is exactly same as
var person = new Person();
person.FirstName = "Bob";
person.LastName = "smith";
And as people said. Your example wont compile. Because its not constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With