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.