inon
inon

Reputation: 1772

C# function with required return value

Is there a way to write a function that requires that who uses it to get the return value?

For example. this will be throw an error:

public int MustUseReturnValueFN() {
   return 1;
}

private void main() {
   MustUseReturnValueFN(); // Error
   int a = MustUseReturnValueFN(); // Not Error
}

Upvotes: 4

Views: 425

Answers (1)

nestedloop
nestedloop

Reputation: 2646

One way to "require" the caller to get a value would be to use out:

public void MustUseReturnValueFN(out int result)
{
   result = 1;
}

static void Main()
{
   int returnValue;
   MustUseReturnValueFN(out returnValue);
   Console.WriteLine(returnValue) // this will print '1' to the console
}

Upvotes: 7

Related Questions