Mdb
Mdb

Reputation: 8568

C#: Convert a generic function to a Func object

I have the following function:

private int GetEnumTypeUnderlyingId<T>()
        {
            return (int)Enum.Parse(typeof(T), Enum.GetName(typeof(T), _franchise.LogonDialog));
        }

I want to convert it to a Func type. I write something like:

Func<int> GetEnumTypeUnderlyingIdFunc<T> = () => (int)Enum.Parse(typeof(T), Enum.GetName(typeof(T), _franchise.LogonDialog));

But this does not work. I am not really comfortable when working with Func<>, Generics and lambda expressions so any help will be greatly appreciated

Upvotes: 1

Views: 168

Answers (2)

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

You can define your own delegate. Here is what you are looking for:

//Your function type
delegate int GetEnumTypeUnderlyingIdFunc<T>();

//An instance of your function type
GetEnumTypeUnderlyingIdFunc<int> myFunction = () => //some code to return an int ;

Also this works too.

//An instance of Func delegate
Func<int> GetEnumTypeUnderlyingIdFunc = () => //some code to return an int;

Upvotes: 2

Richard Friend
Richard Friend

Reputation: 16018

Another solution would be

public Func<int> GetTheFunc<T>(T val)
{
    Func<int> func = () => (int)Enum.Parse(typeof(T),Enum.GetName(typeof(T),val));
    return func;
}

Then

var func = GetTheFunc<_franchise>(_franchise.LoginDialog);

//Now you can use the func, pass it around or whatever..
var intValue = func();

Upvotes: 0

Related Questions