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);
}
}
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
);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With