Lambda and generics function

  • Thread starter Thread starter LiquidNitrogen
  • Start date Start date
L

LiquidNitrogen

Hi guys,

As a new .net generics learner could some one care to explain what is
the difference when i declare the function such as

void function(Action<String> customAction)
{
customAction("rohit");
}

and
void function<String>(Action<String> customAction)
{
customAction("rohit");
}


The below sample program compiles fine but the moment I change Callme
to Callme<String> the compilers throws cannot convert from type
'string' to 'String'.

using System;
using System.Linq;
using System.Linq.Expressions;

public class test
{
public void Callme(Action<String> action)
{
foreach (String name in names)
{
action(name);
}
}

public void func(String name)
{
System.Console.WriteLine(name);
}

String[] names = { "Rohit", "Sharma" };
public string name = "Rohit";
}

public class mainclass
{
public static void Main()
{
test obj = new test();
Action<String> ca = obj.func;

obj.Callme(p => ca(p));
Console.ReadKey();
}
}
 
LiquidNitrogen said:
As a new .net generics learner could some one care to explain what is
the difference when i declare the function such as

void function(Action<String> customAction)
{
customAction("rohit");
}

and
void function<String>(Action<String> customAction)
{
customAction("rohit");
}

Well, the latter is trying to create a generic method with a type
parameter called String. It's as if you'd written:

void function<T>(Action<T> customAction)
{
customAction("rohit");
}

The compiler is complaining because it can't convert from a string to a
T, and customAction takes a T not a string.

I suspect this isn't what you meant to do.

What were you trying to achieve by adding the <String> part?
 
Back
Top