Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value from C# partial method?

Tags:

c#

.net

Is there a way to do so as it seems partial method must return void (I really don't understand this limitation but let it be) ?

like image 699
user310291 Avatar asked Jan 31 '11 23:01

user310291


People also ask

What is return value in C?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.

How do you return in C?

c=a+b; return c; We can replace with single-step like return a+b; If you forget to return a value in a function, it returns the warning message in most of the C compilers.

Can main return a value in C?

Master C and Embedded C Programming- Learn as you go The normal exit of program is represented by zero return value. If the code has errors, fault etc., it will be terminated by non-zero value. In C++ language, the main() function can be left without return value.

What is function should return a value in C?

In C++, a function which is defined as having a return type of void , or is a constructor or destructor, must not return a value. If a function is defined as having a return type other than void , it should return a value.


2 Answers

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.

like image 66
Frédéric Hamidi Avatar answered Oct 16 '22 18:10

Frédéric Hamidi


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.

like image 23
RPM1984 Avatar answered Oct 16 '22 19:10

RPM1984