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:
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.