0

I'm trying to declare a Func<T, TResult> for a static method on a struct that has in parameters.

The signature of my method is something like this:

public static MyStruct MyMethod(in MyStruct input);

I tried to declare the Func this way:

new Func<MyStruct, MyStruct>(MyStruct.MyMethod);

But this causes an error:

"No overload for 'MyMethod' matches delegate Func<MyStruct, MyStruct>."

I did some googling, and found the following information in the Microsoft docs:

The encapsulated method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have one parameter that is passed to it by value, and that it must return a value. (https://learn.microsoft.com/en-us/dotnet/api/system.func-2?view=netcore-3.1)

From my code, I can see this to be true as I have some Funcs working properly for methods on this struct with in parameters, and they have another argument passed by value.

So my question has two parts, firstly why does at least one argument to a Func<> have to be passed by value? And secondly, how can I achieve getting a Func<> which will encapsulate the static method on my struct?

11
  • 1
    Does it have to be a Func<>? Why not simply create your own delegate to pass the method around? Something like public delegate MyStruct MyFunc(in MyStruct input). -- Func<> delegates are basically just that and they are "prepared for your convenience". Commented Jan 27, 2020 at 15:37
  • 2
    I do not think this can be done with Func..... You need to create a delegate Commented Jan 27, 2020 at 15:38
  • 1
    @juharr The parameter modifier in was added in C# 7.2. Commented Jan 27, 2020 at 15:40
  • 1
    @MattB - It's not possible with Func<> (atm?), because there is no Func<> defined like that. See referencesource. For one or two parameters, the framework could provide in variants. But it get's pretty tedious pretty fast with more parameters (could be automated, but then you'd have billions of delegates in intellisense...). Commented Jan 27, 2020 at 15:45
  • 2
    @MattB I have added the c#-7.3 tag since this is a language feature specific to that version. Commented Jan 27, 2020 at 16:02

0

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.