I have a generic method which will accept generic type T. I know that at runtime T will be some type of struct out of a set of structs I have defined previously. I am having trouble figuring out how to instantiate the struct and initialize the fields of the struct.
public void mymethod<T>() {
// T is a struct which I know will have certain fields.
// I want to initialize them in this method
Type type = typeof(T);
System.Reflection.MemberInfo attributes = typeof(T);
//which line is correct, top one or one below?
//System.Reflection.MemberInfo attributes = typeof(T).GetMember("length", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)[0];
}
Do I need to assign a MemberInfo object for each of the fields I know will be present? Or is it possible to just get all the fields of the passed in struct (since I know different structs will have certain different fields that others dont). Also, once I have a field, how do I assign it a value for that particular struct?
Just to make the problem clearer: what I'm trying to accomplish is the following. I know for sure that during runtime my_method will be accepting some sort of struct from a set of structs I have defined in a different class. Here is an example of 2 of those structs:
public struct Struct1 {
public int length;
public int width;
}
public struct Struct2 {
public int length;
public int width;
public int height;
public string color;
}
mymethod() will accept a generic struct as T. I want to assign fields to that struct based on calculations I do in mymethod (which are irrelevant so I haven't shown them here). Each struct has some basic fields (such as in the example above, both Struct1 and Struct2 have length and width, but Struct2 has more attributes). For whatever struct is passed in as T, I want to assign values to its fields. So for example, if Struct2 is passed in to T, then I want to say
struct2.length = 1;
struct2.width = 2;
struct2.height;
struct2.color;
I need to find the generic equivalent of doing the above, so I tried using MemberInfo to achieve this. My question is how can I assign at least the basic fields of whatever struct is passed in? I know that if I said Struct2 struct2 = new Struct2() then all the attributes are initalized but I can't really say typeof(T) somestruct = new typeof(T) So, do I need to initialize MemberInfo objects for each of the fields that may or not be there? I don't think this will work since different structs will have different fields. It is better if there is a way to get all the fields of a struct, initialize them to some basic value (such as what is done when you say Struct2 struct2 = new Struct2()) and then assign actual values to the fields of the struct I know will be there. How do I assign fields to a generic object?