Func delegate with ref variable

32,853

Solution 1

It cannot be done by Func but you can define a custom delegate for it:

public delegate object MethodNameDelegate(ref float y);

Usage example:

public object MethodWithRefFloat(ref float y)
{
    return null;
}

public void MethodCallThroughDelegate()
{
    MethodNameDelegate myDelegate = MethodWithRefFloat;

    float y = 0;
    myDelegate(ref y);
}

Solution 2

In .NET 4+ you can also support ref types this way...

public delegate bool MyFuncExtension<in string, MyRefType, out Boolean>(string input, ref MyRefType refType);
Share:
32,853
chugh97
Author by

chugh97

Updated on July 05, 2022

Comments

  • chugh97
    chugh97 almost 2 years
    public object MethodName(ref float y)
    {
    //method
    }
    

    How do I defined a Func delegate for this method?

  • Eric Lippert
    Eric Lippert about 14 years
    The reason being: all generic type arguments must be things that are convertible to object. "ref float" is not convertible to object, so you cannot use it as a generic type argument.
  • chugh97
    chugh97 about 14 years
    Thanks for that, I was struggling to use Func so I know why I cant use it when type is not convertible to object
  • Mike Johnson
    Mike Johnson over 8 years
    Not to resurrect a dead thread but it should definitely be noted for anyone that comes across this that while you can support a ref param with generics this way, the generic type parameter will be invariant. Generic type parameters don't support variance (covariance or contravariance) for ref or out parameters in c#. Still fine if you don't need to worry about implicit type conversions though.
  • Kyle Baran
    Kyle Baran over 8 years
    Does that mean that the delegate typing will require boxing/unboxing in this case?
  • Glenn Slayden
    Glenn Slayden about 7 years
    Sorry, this answer is a bit off-track. The in and out you're showing for paramerizing the delegate pertain to co- versus "contra-variance", and are not related to what the OP is asking about. The question was about delegates which can accept parameters by reference, not the agility of a (generic) delegate with regard to its type parameteriization.