l--'''''&# February 2016

generalizing 'using' in a functional way

I've been going through my c# code and trying to convert the majority of it to be more functional.

How do you convert this using expression into a more functional-style pattern?

    using (var stream = File.OpenWrite(Path.Combine(settingsFolder, settingsFilename)))
    using (var writer = new someClass(stream))
    {
        writer.Write(settings);
    }

I'm trying to use this functional pattern (replacing using with this Disposable):

public static class Disposable
{
    public static TResult Using<TDisposable, TResult>(
        Func<TDisposable> factory,
        Func<TDisposable, TResult> map)
        where TDisposable : IDisposable
    {
        using (var disposable = factory())
        {
            return map(disposable);
        }
    }
}

Will this pattern not work since the class File is static and sealed?

Answers


Patrick Hofman February 2016

Well, it does work. I am not sure why you would want to do this, but File being static doesn't prevent you in any way to do this. The Func expects a factory delegate, not a class that can be instantiated.

This code should work for you:

Disposable.Using
    ( () => Disposable.Using
                ( () => File.OpenWrite(path)
                , stream => new someClass(stream)
                )
    , writer => { writer.Write(settings); return true; }
    );

There is a problem with disposing though, since the inner using will already dispose. If possible, you should dispose the stream in your someClass. If not possible, just use using.

The return true is solely there for the reason that the Func expects a return type. An Action would be better fitting in this scenario.

Post Status

Asked in February 2016
Viewed 3,586 times
Voted 14
Answered 1 times

Search




Leave an answer