Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading