views:

136

answers:

2

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#?

+4  A: 

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);
ChrisF
Additionally, this is what people are talking about when they say "block level scoping"
Matt
+1  A: 

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).

Dzmitry Huba