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

How do I define a Func delegate for this method?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
chugh97
  • 9,602
  • 25
  • 89
  • 136

2 Answers2

115

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);
}
Elisha
  • 23,310
  • 6
  • 60
  • 75
  • 33
    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. – Eric Lippert Mar 17 '10 at 14:23
  • 1
    Thanks for that, I was struggling to use Func so I know why I cant use it when type is not convertible to object – chugh97 Mar 17 '10 at 15:28
  • 1
    Does that mean that the delegate typing will require boxing/unboxing in this case? – Kyle Baran Nov 12 '15 at 13:21
9

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);
SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173
  • 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. – Mike Johnson Sep 07 '15 at 00:24
  • 5
    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. – Glenn Slayden Apr 29 '17 at 21:30