Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a C# method that will accept an injected dependency of unknown type?

Tags:

c#

.net

.net-4.0

Background

I have a couple of utility methods I would like to add to a solution on which I am working and use of dependency injection would open many more potential uses of said methods.

I am using C#, .NET 4

Here is an example of what I am trying to accomplish (this is just an example):

public static void PerformanceTest(Func<???> func, int iterations)
{
    var stopWatch = new Stopwatch();
    stopWatch.Start();
    for (int i = 0; i < iterations; i++)
    {
      var x = func();
    }
    stopWatch.Stop();

    Console.WriteLine(stopWatch.ElapsedMilliseconds);
}

What I have done here is create a method to test the performance of certain elements of my code when debugging. Here is an example of how you would use it:

Utilities.PerformanceTest(someObject.SomeCustomExtensionMethod(),1000000);

Question

The "PerformanceTest" method expects to be passed (injected) a function of known type. But what if I want "PerformanceTest" to allow injection of various functions that return various types? How do I do that?

like image 381
Matt Cashatt Avatar asked Oct 11 '12 17:10

Matt Cashatt


3 Answers

Can't it be just generic?

public static void PerformanceTest<T>(Func<T> func, int iterations)
{
    var stopWatch = Stopwatch.StartNew();
    for (int i = 0; i < iterations; i++)
    {
        T x = func();
    }
    stopWatch.Stop();

    Console.WriteLine(stopWatch.ElapsedMilliseconds);
}

Also if you don't care of what type is the argument, you can pass Func<object>, can't you?

like image 59
abatishchev Avatar answered Nov 07 '22 21:11

abatishchev


I would change your PerformanceTest method to this:

public static void PerformanceTest(Action func, int iterations)

End than call:

Utilities.PerformanceTest(() => someObject.SomeCustomExtensionMethod(),1000000);

This will probably increase the time, because of lambda expression, but I can´t say how or if this is even important,

like image 39
Ondra Avatar answered Nov 07 '22 20:11

Ondra


Use generics:

public static void PerformanceTest<T>(Func<T> func, int iterations)
{
    var stopWatch = new Stopwatch();
    stopWatch.Start();
    for (int i = 0; i < iterations; i++)
    {
      var x = func();
    }
    stopWatch.Stop();

    Console.WriteLine(stopWatch.ElapsedMilliseconds);
}
like image 2
Furqan Safdar Avatar answered Nov 07 '22 20:11

Furqan Safdar