-8

How do I delete a variable that is once declared and defined?

For example, in C++ I would do:

int x;

..

delete x;

How can I do it in C#?

(i need to do something like this:

switch (something)
{
case 1:
int Number;
break;

case 2:
float Number;
break;
}

But I can't do it, because Number is already taken by case 1... And I want the same name, so I want to delete int Number before float Number is declared, so compilator won't shout at me. ;p

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
Acrivec
  • 11
  • 5

1 Answers1

7

You can make the scopes non-overlapping using braces:

switch (something)
{
  case 1: {
    int Number;
  }
  break;

  case 2: {
    float Number;
  }
  break;
}

Going out of scope is the only way a variable name is "deleted" in the sense you are talking about. Notably and unlike some other languages, C# doesn't allow hiding local variables with other variables in more limited scopes -- the scopes have to be non-overlapping (and in C#, that means from the opening brace, not simply the point of declaration!). What I mean is that this code, which is legal in C and C++ (not sure about Java) will cause a compiler error in C#:

int Number;
{
    float Number;
}
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • I've thinked about it at the beginning of the problem, and Visual Studio keeps crying. :/ //edit: Oh wait, I added bracers to case 1, but not to case 2, that's the problem... :P Thanks. – Acrivec Oct 20 '14 at 19:23