views:

480

answers:

4

I'm just curious...

Is it possible to release a variable in c#?

What I mean is, can you do something like this:

...
string x = "billy bob";

//release variable x somehow

string x = "some other string";

//release variable x somehow

int x = 329;
...

... so basically you are declaring the variable multiple times in the same scope.

If this isn't possible in c#, what languages is it possible in?

+12  A: 

You can do it with scopes (loose term; formally I believe this would be a declaration space), e.g. the following is perfectly legal C# within a method body:

{
    string x = "billy bob";    
}
{
    string x = "some other string";
}
{
    int x = 329;
}

I wouldn't advise writing code like this though, it makes it far too easy to get variables confused in a method. Better to use different, more descriptive names, or separate each block out into its own method.

Greg Beech
It seems that you've read Eric Lippert's latest blog post ;)
Thomas Levesque
@Thomas - Indeed I have :-)
Greg Beech
legal but just plain nasty...*eye stab*
Nathan W
+9  A: 

No, this isn't possible in C# within the same scope - for which I'm very grateful. It sounds like a recipe for readability disaster. As Greg has shown, you can introduce your own scopes within a method solely for this purpose though.

I don't know which languages allow you to do this - weakly typed languages will often let you assign arbitrary values of course, but I don't know of a language which has explicit variable declarations with type information and also allows a redeclaration in the same scope.

You might want to read Eric Lippert's most recent blog post, which is all about scope. (If you don't already read Eric's blog, you might want to clear out a few days in your calendar and read all the back posts... or at least the ones since he joined the C# team. Prepare to have your mind blown repeatedly.)

Jon Skeet
+2  A: 

you can reuse a string:

string x = "billy bob";

x = "some other string";

Why would you want to do this?

Maybe you can do this:

object x = "billy bob"

x = "some other string";

x = 329;

Then cast it as you like?

Mark Redman
A: 

You can reassign variables, of course:

string s = "billy bob";
s = "something else";

You can't redeclare variables in the same scope:

// This is illegal:
string s = "billy bob";
string s = "foo"

Since Object is the root of the type system in .NET, you can do something like this:

object o = "billy bob";
o = "foo";
o = 5;
Judah Himango