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

10,371

Solution 1

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();
    }
}

Solution 2

That's possible using reflection as BigYellowCactus has shown. But there's no need to do this in the constructor every time as the number of properties never changes.

I would suggest doing it in a static constructor (called only once per type):

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

    private static readonly int _propertyCount;

    static MyClass()
    {
        _propertyCount = typeof(MyClass).GetProperties().Count();
    }
}

Solution 3

public MyClass()
{
    int count = GetType().GetProperties().Count();
}
Share:
10,371
miri
Author by

miri

Updated on July 22, 2022

Comments

  • miri
    miri almost 2 years

    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