How do I overwrite a variable in C# with a value of another type?

Viewed 315

In Python, I was used to doing stuff like this without the compiler complaining:

test = "Hello"
test = 1

I am now trying to learn C#, but it will not allow me to overwrite variables like that, since they have different types:

string test = "Hello";
int test = 3;

The above snippet will throw an error:

Error CS0128 A local variable or function named 'test' is already defined in this scope

One possible workaround is to do something like this:

string testString = "Hello";
int testInt = 3;

But I believe this to be poor practice for two reasons:

  • It forces you to have one variable per type, even in cases where you don't need the first type anymore
  • It allocates memory to a type which is not needed anymore in the code.

Is there really no clean way to overwrite variables or their types in C#? I have grown quite accustomed to doing this in python and it allows for clean code in my opinion.

1 Answers

C# is a statically-typed language, which means once you declared a variable, you cannot change its type.

For example, take int x=12;. x just accepts numeric values; you cannot store string like "osman" in it.

You can use dynamic like below:

dynamic test = "osman";
test = 2;
test = 3.4;
Related