Search code examples
c#using

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


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.


Solution

  • 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());