Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I cast String func(SomeEnum) to a Func<Enum, String>?

Tags:

c#

func

.net-4.0

I think this has something to do with the whole variance thing, but I don't quite get why this isn't allowed.

I have a method

public void method(Func<Enum, String> func)

And I have a few different methods such as

public String doSomething(someEnum)
public String doSomethingElse(someOtherEnum)

I want to make calls like this

method(doSomething)
method(doSomethingElse)

but I get these errors

convert from 'method group' to System.Func<System.Enum,string>

What is the reason this cannot be done? Do I really need to rewrite method into multiple methods like this?

public void method(Func<someEnum, String> func)
public void method(Func<someOtherEnum, String> func)

That's really ugly.

edit:

I want to do something like this in the method (note in my actual code, enumType is also passed in as a Type)

foreach (Enum val in Enum.GetValues(enumType))
{
      func(val);
}
like image 716
Erix Avatar asked Feb 22 '23 14:02

Erix


1 Answers

you could perhaps get away with

 public void method<TEnum>(Func<TEnum, String> func)

or you can define a generic delegate:

 delegate String MyFunc<T>(T);

I think (haven't tried) in C# 4.0 you can use co-/contravariance with that:

 delegate String MyFunc1<in  T>(T);
 delegate String MyFunc2<out T>(T);

Which should mean that you'd be able to assign MyFunc<Derived> to MyFunc<Base>


Edit I have just found out that indeed covariance cannot be made to work for enums, as you would not be able to specify the type constraint:

delegate string Display<in T>(T v) where T : Enum;

Yields:

 test.cs|5 col 50 error 702| A constraint cannot be special class `System.Enum'

So because you cannot derive Enum2 from Enum1, you're stuck with invariant generic Enums. Bugger.

like image 173
sehe Avatar answered Feb 25 '23 05:02

sehe