How do you give a C# Auto-Property a default value, using a custom attribute?
This is the code I want to see:
class Person
{
[MyDefault("William")]
public string Name { get; set; }
}
I am aware that there is no built in method to initialize the default using an attribute – can I write my own custom class that uses my custom attributes to initialize the default?
You could use a helper class like that:
And call
InitializeDefaultValuesin the constructor of your class.EDIT: updated version, which generates and caches a delegate to do the initialization. This is to avoid using reflection every time the method is called for a given type.