0

I had recently created a function to make loading multiple classes, while benchmarking the loading time easier with a simple method. I would like to know how I can extend this to allow multiple parameters passed to the method itself, and multiple parameters to the T (The class you're loading)

Method:

public static T CreateInstanceOf<T>() where T : new()
{
    var stopwatch = Stopwatch.StartNew();
    var result = new T();

    stopwatch.Stop();
    Logger.Trace("Loaded " + result.GetType().Name + " [took " + stopwatch.ElapsedMilliseconds + "ms]");

    return result;
}


Current Usage:

_myClass = Utilities.Utilities.CreateInstanceOf<MyClass>();


Now, lets say that the class 'MyClass' had a public constructor, with multiple parameters, something like this

public MyClass(string name, int age, bool eating)

How could I extend the functionality to allow myself to send parameters to the class I am loading's constructor?

I would also like to pass extra parameters to the method itself, to include in the Logger.Trace line, can this be done?

Many Thanks, Seriosk.

Beefo
  • 507
  • 1
  • 6
  • 13
  • There is an old feature request for this feature: https://github.com/dotnet/roslyn/issues/2206 – xanatos Mar 18 '17 at 13:05
  • And a similar question here: http://stackoverflow.com/questions/840261/passing-arguments-to-c-sharp-generic-new-of-templated-type – xanatos Mar 18 '17 at 13:07
  • And here: http://stackoverflow.com/questions/853703/how-to-constrain-generic-type-to-must-have-a-construtor-that-takes-certain-param – xanatos Mar 18 '17 at 13:08
  • @MickyD Through reflection you can do anything... But note the ***while benchmarking** the loading time*... Reflection adds quite much to constructor calling... I'll quote the most upvoted comment comment: *Cautionary conclusion would be that Activator.CreateInstance **is taking roughly 11 times as much time** to do the same job as a new T() does, and a delegate takes roughly 1.5 times as much.* – xanatos Mar 18 '17 at 13:15
  • @xanatos I know, I'm the one who added the note on the link –  Mar 18 '17 at 13:17
  • But yes, rereading what I wrote, what I really meant was: you can't have a constraint of type `new(x, y, z)`, so you can't use `new` constraint with multiple parameters... There are other worse solutions. – xanatos Mar 18 '17 at 13:17
  • @MickyD *I know, I'm the one who added the note on the link* :-) :-) :-) :-) – xanatos Mar 18 '17 at 13:18
  • @xanatos haha. No worries there buddy :) –  Mar 18 '17 at 13:19

0 Answers0