Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, is there 'Defer Call' like golang?

Tags:

c#

destructor

golang support 'Defer Call' and when c++, I use this trick(?).

struct DeferCall
{
   DeferCall() {}
   ~DeferCall() { doSomeThing(); }
}

void SomeMethod()
{
    DeferCall deferCall;
    ...
}

how can I do this in c# ?

I need like this golang defer tutorial

like image 812
ekflame Avatar asked Nov 19 '16 07:11

ekflame


1 Answers

The nearest language equivalent will be try-finally:

try
{
    DoSomething();
}
finally
{
    DoCleanup();
}

The nearest framework equivalent will be IDisposable + using:

using (var stream = File.OpenRead("foo.txt"))
{
    // do something
}

Personally, defer term confuses me, since this is not "deferred execution" (schedule now - execute later, which could be implemented via tasks), but some sort of RAII implementation.

P.S. Assuming, that you will continue to learn golang:

  • panic equivalent is throw
  • recover equivalent is catch
like image 131
Dennis Avatar answered Sep 30 '22 20:09

Dennis