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

How do I define a Func delegate for this method?

2 Answers 2

123

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Thanks for that, I was struggling to use Func so I know why I cant use it when type is not convertible to object
Does that mean that the delegate typing will require boxing/unboxing in this case?
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);

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.