Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 585
inon Avatar asked Mar 22 '23 04:03

inon


1 Answers

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
}
like image 89
nestedloop Avatar answered Apr 01 '23 10:04

nestedloop