I know, but in my case I am retrieving the type of a property using
reflection, and that is the type that I need to pass to the generic
DoSomething, so no point to make the initial call generic. The other
option is to make a non-generic version of DoSomething and just eat
the performance impact of the boxing.
If you're already using reflection, boxing should be the least of your performance
worries. :-) Second of all, the generic constraints that you've applied to
DoSomething<Tensure that their won't be any boxing operations because only
reference types can be used with it. And finally, if you're using reflection,
you *could* use reflection to dynamically set the generic argument to your
method and invoke it like this:
using System;
using System.Reflection;
namespace ConsoleApp
{
class Program
{
class A
{
T DoSomething<T>() where T: class, new()
{
T ThisObj = new T();
// Do something usefull...
return ThisObj;
}
public void StartHere(Type type)
{
MethodInfo method = this.GetType().GetMethod("DoSomething", BindingFlags.NonPublic
| BindingFlags.Instance);
MethodInfo closedMethod = method.MakeGenericMethod(type);
object o = closedMethod.Invoke(this, null);
}
}
static void Main(string[] args)
{
new A().StartHere(typeof(A));
}
}
}
Of course, if the "class" generic constraint isn't used, there would potentially
be boxing because the Invoke() method returns a System.Object.
Best Regards,
Dustin Campbell
Developer Express Inc.