Func delegate with ref variable
Asked Answered
S

2

77
public object MethodName(ref float y)
{
    // elided
}

How do I define a Func delegate for this method?

Sfumato answered 17/3, 2010 at 14:4 Comment(0)
P
118

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);
}
Pontificals answered 17/3, 2010 at 14:7 Comment(3)
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.Lab
Thanks for that, I was struggling to use Func so I know why I cant use it when type is not convertible to objectSfumato
Does that mean that the delegate typing will require boxing/unboxing in this case?Eyelid
L
10

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);
Lapierre answered 4/6, 2014 at 18:20 Comment(2)
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.Tabling
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.Redwine

© 2022 - 2024 — McMap. All rights reserved.