Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I count properties before I create an object? In the constructor?

can I count the amount of properties in a class before I create an object? Can I do it in the constructor?

class MyClass
{  
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }

    public MyClass()
    {
        int count = //somehow count properties? => 3
    }
}

Thank you

like image 370
miri Avatar asked Jul 24 '12 14:07

miri


1 Answers

Yes, you can:

class MyClass
{  
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }

    public MyClass()
    {
        int count = this.GetType().GetProperties().Count();
        // or
        count = typeof(MyClass).GetProperties().Count();
    }
}
like image 155
sloth Avatar answered Sep 20 '22 14:09

sloth