August
August

Reputation: 13

Func<T,T> action as a parameter for a function with <T>, and how to write the body?

I have a class as follows. I just want to get the function testa and testb to get same result, testa has explicit type string with it, while generic type is defined for testb:

public class testclass
{
    public void testa(Func<String, String> action)
    {

        Console.WriteLine(action("what?"));
    }

    public void testall()
    {
        testa(tc =>
        {
            return tc;
        });

        testb<string>(tc =>
        {
            return tc;
        });
    }

    public void testb<T>(Func<T, T> action)
    {

         **//How to write the body here to get the same result as testa do
         //like action("abc");?**
    }

}

Upvotes: 1

Views: 134

Answers (1)

Jamiec
Jamiec

Reputation: 136104

You dont know what T is in testb, so you cant provide a concretete value, except default(T):

public void testb<T>(Func<T, T> action)
{
    action(default(T)); // null for reference types, 0 for ints, doubles, etc    
}

Another option would be to provide the test value to testb

public void testb<T>(Func<T, T> action, T testValue)
{
    action(testValue);        
}

public void testall()
{
    testa(tc =>
    {
        return tc;
    });

    testb<string>(tc =>
    {
        return tc;
    }, "abc"); // now same result as testa
}

A third option, is to provide the constraint new() to T, and then you could construct one:

public void testb<T>(Func<T, T> action) where T : new()
{
    action(new T());        
}

Little sidenote: As commented, action is a usually name given to a function expression which has no return (ie Action<T> or Action<string> etc). It makes no difference to your code, but may confuse other programmers. We're a pedantic lot!

Upvotes: 5

Related Questions