Carl
Carl

Reputation: 723

C# - Trying construct a class from a function, getting Cannot convert method group error

I'm trying to encapsulate a function inside a class but it's not working. What am I missing here?

public class MyClass<Return, T>
{
        public delegate void D01(T val);
        public D01 d01;
        public delegate void D02(T val, T val2);
        public D02 d02;
 
        public MyClass(D01 func)
        {
            d01= func;
        }

        public MyClass(D02 func)
        {
            d02= func;
        }
    }

    public class ABC
    {
   
        public void MyGenericFunction<T>(MyClass<T, T> function, T var01)
        {
            ...
        }
    }

    class OtherClass
    {
        private ABC abc = new ABC();
        private void Test(float x) {...}
        private void OtherFunc()
        {
            float x = 1.0f;
            abc.MyGenericFunction<float>(Test, x);
            //Gives Cannot convert method group to MyClass<float,float> error
        }
    }

It should be able to convert function to the delegate of the same type. I also have the same constructor with Func and Action parameters but couldn't get them to work either.

Upvotes: 0

Views: 81

Answers (1)

TheGeneral
TheGeneral

Reputation: 81513

Woah, heaps of stuff going on here.. I guess you actually want Func apposed to MyClass<T, T> function

public void MyGenericFunction<T>(Func<T, T> function, T var01)
{
   ...
}

...

private float Test(float x)
{
   ...
}

private void OtherFunc()
{
   float x = 1.0f;
   abc.MyGenericFunction<float>(Test, x);
}

On the off chance you actuall want

public void MyGenericFunction<T>(MyClass<T, T> function, T var01)

Then youd likely want something more like this

abc.MyGenericFunction<float>(new MyClass<float, float>(Test), x);

Upvotes: 1

Related Questions