Let's say I have some piece of code that I want to reuse. This piece of code has the property that it either returns something or that it modifies some data but does not return anything. Because of that, I cannot make it a usual method (return type void
is wrong since it might return, and any return type is wrong as well since it might not return).
Does C# support that kind of "method" in any way, i.e. allows to encapsulate and reuse such a piece of code somehow?
Below is an example use case:
I have an interface ITree<T>
and many classes T
implementing ITree<T>
.
interface ITree<T>
{
public T Child;
public bool Ignore;
}
I have a lot of methods that take an object of some type T
implementing ITree<T>
as argument and that have some class as return type.
Almost all of these methods look like this:
MyClass2 SomeMethod(MyClass1 input) // MyClass1 implements ITree<MyClass1>
{
while (input.Ignore)
{
input = input.Child;
if (input == null)
return null;
}
... // do MyClass1 specific stuff and finally return some instance of MyClass2
}
Because the while loop is the same everywhere, I would like to encapsulate it in a "method", like this:
... WhileLoop<T>(ref ITree<T> input)
{ // can't specify return type because it might return null or nothing at all
while (input.Ignore)
{
input = input.Child;
if (input == null)
return null;
}
}
MyClass2 SomeMethod(MyClass1 input)
{
WhileLoop(ref input);
// either returns null or changes input so that input can be used below
... // do MyClass1 specific stuff and finally return some element of MyClass2
}
But since this "method" may or may not return something, it cannot be a method in the usual sense.
There is no keyword for "voidable return" of a function. C# does not support that, and I don't think any language does, since it would break encapsulation (the calling method should know what the return value would be in advance to get or not get the result). The only alternative you have are, returning null, ignoring the output of the function or making a void method that has an output parameter.