Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection to get properties of an instance of a class at runtime C#

Tags:

c#

reflection

Hi here is what I am trying to do, I have a class (EventType) which can be dynamic and have different members/properties at different times.

class EventType
{
    int id{set;}
    string name{set;}
    DateTime date{set;}
    List<int> list{set;}
    Guid guid{set;}
}

In my main method I am passing an instance on this class to a to a function in a different class and trying reflection to get the properties of the instance but its not successful and giving me null value.

class Program
{
    static void Main(string[] args)
    {
        EventType event1 = new EventType();
        int rate = 100;
        DataGenerator.Generate<EventType>(event1, rate);
    }
    public static byte[] test(EventType newEvent)
    {
        return new byte[1];
    }
}



static class DataGenerator
{
    public static void Generate<T>(T input, int eventRate, Func<T, byte[]> serializer=null)
    {            
        Type t = input.GetType();
        PropertyInfo[] properties = t.GetProperties();
        foreach (PropertyInfo property in properties)
        {
            Console.WriteLine(property.ToString());   
        }
        var bytes = serializer(input);
    }
}
like image 837
MJSHARMA Avatar asked Feb 16 '23 09:02

MJSHARMA


2 Answers

Your class properties are private by default, and GetProperties only return public properties.

Either promote your properties as public :

class EventType
{
    public int id{set;}
    public string name{set;}
    public DateTime date{set;}
    public List<int> list{set;}
    public Guid guid{set;}
}

Or specify binding flas to get non-public properties :

Type t = input.GetType();
PropertyInfo[] properties = t.GetProperties(
    BindingFlags.NonPublic | // Include protected and private properties
    BindingFlags.Public | // Also include public properties
    BindingFlags.Instance // Specify to retrieve non static properties
    );
like image 55
Steve B Avatar answered May 12 '23 00:05

Steve B


Type.GetProperties returns the public properties of a type. But since you haven't specified whether the access type of your properties they are private.

You can use the overloaded Type.GetProperties(BindingFlags) method to get all properties, regardless of their access modifier.

like image 42
Dirk Avatar answered May 11 '23 22:05

Dirk