Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to neglect/drop a c# "out" variable?

Tags:

c#

Say I have been provided a function that looks something like this:

int doSomething(int parameter, out someBigMemoryClass uselessOutput) {...}

I want to use this function but I don't need the uselessOutput variable at all. How can I get the function to work without using the uselessOutput, preferably without allocating any new memory?

like image 445
Scar Avatar asked Jul 22 '16 10:07

Scar


2 Answers

Simply put - you can't. Either pass a variable and ignore the out afterwards (if the memory hit from allocating the out parameter is tiny, i.e., not a big memory class) or edit the code for the function yourself.

One way I thought of just now actually is to wrap the function too, if its annoying having to pass an ignored out variable all the time. It doesn't get rid of the out for the original function, but it provides us a way to call the function without caring about the out variable at all.

class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void MethodWrapper() 
    {
        int i = 0;
        Method(out i);
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44

        MethodWrapper();
        // No value needed to be passed - function is wrapped. Method is still called within MethodWrapper, however.
    }
}

This, however, doesn't solve your big memory class issue, should you call this a lot of times. For that, you would need to rewrite the function. Calling it within the wrapper function would still require the same memory allocation unfortunately.

like image 189
Nick Bull Avatar answered Nov 05 '22 00:11

Nick Bull


There is no way to simply omit an out parameter, but you can make your life a little more comfortable by wrapping your method in an extension method that doesn't have the out parameter:

// let's assume the method in question is defined on type `Foo`:
static class FooExtensions
{
    public static int doSomething(this Foo foo, int parameter)
    {
        someBigMemoryClass _;
        return foo.doSomething(parameter, out _);
    }
}

Then call that extension method instead of the actual instance method:

Foo foo = …;
int result = foo.doSomething(42);

(And whenever you do want to specify the out parameter, you still can, because the original method is still there.)

Of course the original method will still produce the unneeded someBigMemoryClass object, which might be a (hopefully short-lived) waste of resources. Better to change the original method directly, if that is an option.

like image 26
stakx - no longer contributing Avatar answered Nov 05 '22 01:11

stakx - no longer contributing