简体   繁体   中英

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

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM