Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# using statement with return value or inline declared out result variable

Tags:

c#

using

I am wondering if there is some way to optimize the using statement to declare and assign its output together (when it is a single value).

For instance, something similar to the new way to inline declare the result variable of an out parameter.

//What I am currently doing:
string myResult;
using(var disposableInstance = new myDisposableType()){
    myResult = disposableInstance.GetResult();
}

//That would be ideal
var myResult = using(var disposableInstance = new myDisposableType()){
    return disposableInstance.GetResult();
}

//That would be great too
using(var disposableInstance = new myDisposableType(), out var myResult){
    myResult = disposableInstance.GetResult();
}

Thanks for your input.

like image 586
Harps Avatar asked Mar 02 '18 11:03

Harps


2 Answers

You can use extension method to "simplify" this usage pattern:

public static class Extensions {
    public static TResult GetThenDispose<TDisposable, TResult>(
        this TDisposable d, 
        Func<TDisposable, TResult> func) 
            where TDisposable : IDisposable {

        using (d) {
            return func(d);
        }
    }
}

Then you use it like this:

string myResult = new myDisposableType().GetThenDispose(c => c.GetResult());
like image 179
Evk Avatar answered Sep 21 '22 21:09

Evk


This is funny, because I started reading Functional Programming in C# a couple of days ago, and one of the first examples is along the lines of:

public static TResult Using<TDisposable, TResult>(TDisposable disposable, Func<TDisposable, TResult> func) 
    where TDisposable : IDisposable
{
    using (disposable)
    {
        return func(disposable);
    }
}

Usage:

 var result = Using(new DbConnection(), x => x.GetResult());

Notice that, unlike the other answers posted, this function has absolutely no responsibility but get the result of func, regardless of TDisposable.

like image 41
Camilo Terevinto Avatar answered Sep 22 '22 21:09

Camilo Terevinto