What is the value of an anonymous unattached block in C#?

后端 未结 10 1635
谎友^
谎友^ 2021-01-11 20:43

In C# you can make a block inside of a method that is not attached to any other statement.

    public void TestMethod()
    {
        {
            string x          


        
10条回答
  •  猫巷女王i
    2021-01-11 20:50

    In C# -- like c/c++/java -- braces denote a scope. This dictates the lifetime of a variable. As the closing brace is reached, the variable becomes immediately available for a garbage collection. In c++, it would cause a class's destructor to be called if the var represented an instance.

    As for usage, the only possible use is to free up a large object but tbh, setting it to null would have the same effect. I suspect the former usage is probably just to keep c++ programmers moving to managed code somewhat in familiar and comfortable territory. If really want to call a "destructor" in c#, you typically implement the IDisposable interface and use the "using (var) {...}" pattern.

    Oisin

提交回复
热议问题