views:

30

answers:

1

I have a piece of code that looks like this:

    public static T CreateSomething<T>(SomeType a) where T : SomeMicrosoftBaseClass, new()
 {
  var newElement = new T { SomeProperty = a};
  DoStuff();
  return newElement;
 }

and now I need to change the code so I could pass to the constructor of SomeMicrosoftBaseClass a boolean argument - which I can only set on construction.

since the "new()" constraint requires a public parameter-less constructor, and since I couldn't use an interface or modify SomeMicrosoftBaseClass, I'm using reflection like so:

var newElement = (T) (typeof (T).GetConstructor(new Type[] { typeof(SomeType) }).Invoke(new object[] { a }));

can anybody suggest a more elegant way to do this?

+2  A: 

Maybe you can use Activator.CreateInstance:

var newElement = (T)Activator.CreateInstance(typeof(T),a);
Konamiman