Search code examples
c#variablescasting

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


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


Solution

  • 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:)