c# - generalizing 'using' in a functional way -


i've been going through c# code , trying convert majority of more functional.

how convert using expression 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 use functional pattern (replacing using disposable):

public static class disposable {     public static tresult using<tdisposable, tresult>(         func<tdisposable> factory,         func<tdisposable, tresult> map)         tdisposable : idisposable     {         using (var disposable = factory())         {             return map(disposable);         }     } } 

will pattern not work since class file static , sealed?

well, work. not sure why want this, file being static doesn't prevent in way this. func expects factory delegate, not class can instantiated.

this code should work you:

disposable.using     ( () => disposable.using                 ( () => file.openwrite(path)                 , stream => new someclass(stream)                 )     , writer => { writer.write(settings); return true; }     ); 

there problem disposing though, since inner using dispose. if possible, should dispose stream in someclass. if not possible, use using.

the return true solely there reason func expects return type. action better fitting in scenario.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -