How to return value from C# partial method?

Well, technically you can "return" a value from a partial method, but it has to be through a ref argument, so it's quite awkward:

partial void Foo(ref int result);

partial void Foo(ref int result)
{
    result = 42;
}

public void Test()
{
    int i = 0;
    Foo(ref i);
    // 'i' is 42.
}

In that example, the value of i won't change if Foo() is not implemented.


From MSDN:

  • Partial method declarations must begin with the contextual keyword partial and the method must return void.

  • Partial methods can have ref but not out parameters.

So the answer is no, you can't.

Perhaps if you explain a bit more about your situation (why you need to return a value, why the class is partial), we can provide a workaround.


You cannot return a value from a partial method.

Partial methods may or may not be implemented. If it were permitted to return a value from such a method, then what would the caller receive?

Tags:

C#

.Net