'How to initialize get-only property C#
I have a class like this:
public class Customer
{
public int Id { get; set; }
public string FullName { get; set; }
public string Address{ get; }
}
How may I initialize an instance of this class and setup the 'Address' get-only property value? I've tried with
var customer = new Customer
{
Id = 228,
FullName = "Peter",
Address = "Kreshatik",
};
but it it doesn't work.
Please, note that it's not my class and I have no ability to change anything there.
Solution 1:[1]
Absolutely agree with previous answer by @rfmodulator , under given circumstances reflection is the only possible solution. My steps to resolve this issue would be:
- check for parameters in all constructors
- check for public setter methods
- if you have access to source code, check for Address references (maybe the original purpose was something completely different and there is a reason why its setter is restricted)
- contact author
- reflection
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sonyck |
