Matt Cashatt
Matt Cashatt

Reputation: 24208

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

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?

Upvotes: 7

Views: 270

Answers (3)

Ondra
Ondra

Reputation: 1647

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,

Upvotes: 6

Furqan Safdar
Furqan Safdar

Reputation: 16698

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);
}

Upvotes: 2

abatishchev
abatishchev

Reputation: 100258

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?

Upvotes: 9

Related Questions