Home > Blockchain >  Can't we typecast in C# like below as in python
Can't we typecast in C# like below as in python

Time:07-11

I am a newbie and forgive me if this is very basic question. In python, below is possible.

x = 0
x = float(x)

Can't we do this in C#? It throws error unless I assign the casting to a different variable

CodePudding user response:

So in C# when defining a variable, you need to specify the type. For example:

int x = 0

When you typecast in C#, you need to initialize a new variable of a different type, and set it to the existing variable. To type convert the above line to a float we'd add:

float y = x

This is called type conversion, it's where the compiler automatically converts the type of a data structure given the context of the code. Type casting is when the programmer specifically specifies the type which he wishes a variable to be converted to. For instance:

double x = 3.333;
int y;
y = (int)x;

I hope that helped:)

CodePudding user response:

int i = 0;
float f = Convert.ToSingle(i);

CodePudding user response:

you can do that

x = 0
x = float(x)

in c#

int x = 0;
float x2 = (float)x;

You can't change variable type in c#

  • Related