C #: binding to a specific binding scope

Some languages ​​have things like this:

Lisp:

(let ((x 3))
  (do-something-with x))

      

JavaScript:

let (x = 3) {
  doSomethingWith(x);
}

      

Is there anything like this in C #?

+2


source to share


2 answers


You can limit the scope of a value type variable with curly braces.

{
    var x = 3;
    doSomethingWith(x);
}
generateCompilerError(x);

      

The last line will generate a compiler error as it is x

no longer defined.



This will work for object types as well, but does not guarantee when the object will be deleted after it falls out of scope. To ensure that object types that implement IDisposable are positioned in a timely manner, use using

:

using (var x = new YourObject())
{
    doSomethingWith(x);
}
generateCompilerError(x);

      

+6


source


You can use block and area names. From the C # spec:



8.2 Locks

A block allows you to write multiple statements in contexts where one statement is allowed.

block: {statement-listopt}

The block consists of an optional list of statements (§8.2.1) enclosed in braces. If the operator list is omitted, the block is considered empty.

A block may contain a declaration (§8.5). The scope of a local variable or constant declared in a block is a block.

Within a block, the meaning of a name used in the context of an expression must always be the same (§7.5.2.1).

+1


source







All Articles