jeudi 7 septembre 2017

How do i set default values to all Properties of a class in a method or constructor?

So, my wish is to have a constructor (or a method) That would set all my class properties to default values. I've got here so far:

class TestClass
{
    public enum MyEnum { En1, En2, En3}
    public string MyString { get; set; }
    public int MyInt { get; set; }
    public MyEnum MyEnums { get; set; }
    public TestClass()
    {
        var Properties = this.GetType().GetProperties();
        foreach (var Property in Properties)
        {
            Property.SetValue(this,default(Property.GetType()));
        }           
    }
}

I am getting this error: "'Property' is a variable but is used like a type" (CS0118). I know i could use struct for this purpose. But is it actually possible to do something like this? Or I would have to write for each property something like: MyString = default(string), MyInt = default(int)...?

Thanks for any advice :)





Aucun commentaire:

Enregistrer un commentaire