简体   繁体   中英

C#: Scope-specific variable binding

In some languages, there are things like these:

Lisp:

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

JavaScript:

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

Is there anything like this in C#?

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

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

The last line will generate a compiler error as x is no longer defined.

This will work for object types as well, but doesn't guarantee when the object will be disposed after it falls out of scope. To ensure that object types which implement IDisposable are disposed in a timely manner use using :

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

You can use block to scope names. From C# Specification:

8.2 Blocks

A block permits multiple statements to be written in contexts where a single statement is allowed.

block: { statement-listopt }

A block consists of an optional statement-list (§8.2.1), enclosed in braces. If the statement list is omitted, the block is said to be empty.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM