I am writing a system which requires me to fetch the values of properties in an object, preferably using reflection. This project is for the xbox360, which runs on the compact framework and thus has a slow garbage collector - this means it's absolutely vital that I avoid allocations!
The only way I have found to do this is:
Foo Something; //an object I want to get data from
PropertyInfo p; //get this via reflection for the property I want
object value = p.GetGetmethod().Invoke(Something, null);
//Now I have to cast value into a type that it should be
I dislike this for 2 reasons:
- Casting is for potters, generics is for programmers
- It obviously creates garbage every time I have to get a primitive value and it gets boxed.
Is there some generic method for getting the value from a property, which will not box primitives?
EDIT:: In response to Jons answer, this code stolen from his blog does not cause allocations, problem solved:
String methodName = "IndexOf";
Type[] argType = new Type[] { typeof(char) };
String testWord = "TheQuickBrownFoxJumpedOverTheLazyDog";
MethodInfo method = typeof(string).GetMethod(methodName, argType);
Func<char, int> converted = (Func<char, int>)Delegate.CreateDelegate
(typeof(Func<char, int>), testWord, method);
int count = GC.CollectionCount(0);
for (int i = 0; i < 10000000; i++)
{
int l = converted('l');
if (GC.CollectionCount(0) != count)
Console.WriteLine("Collect");
}