Type cast clarification

  • Thread starter Thread starter Raj
  • Start date Start date
R

Raj

What is the difference between these two statments? why is one of the
statement (the second one)is not working??

int a=int.Parse(Console.ReadLine());
int a=(int)Console.ReadLine();

Thank you

Regards
Raj
 
What is the difference between these two statments? why is one of the
statement (the second one)is not working??
Because:

int a=int.Parse(Console.ReadLine());

The above is not a cast. It is an explicit call to the int.Parse()
method, which specifically takes as input a string, and parses it to an
int that the string represents.
int a=(int)Console.ReadLine();

The above is a cast. And since the return value from Console.ReadLine()
is a string, which has no direct conversion to an int, the cast fails.

Pete
 
Thank you

Regards
raj

Peter Duniho said:
The above is not a cast. It is an explicit call to the int.Parse()
method, which specifically takes as input a string, and parses it to an
int that the string represents.


The above is a cast. And since the return value from Console.ReadLine()
is a string, which has no direct conversion to an int, the cast fails.

Pete
 
Peter Duniho said:
[...]
int a=(int)Console.ReadLine();

The above is a cast. And since the return value from Console.ReadLine()
is a string, which has no direct conversion to an int, the cast fails.

Pete

so even if it returned "1" casting to int won't work?
how would one cast strings representing numbers to the number type?
thanks
mark
 
mp said:
Peter Duniho said:
[...]
int a=(int)Console.ReadLine();
The above is a cast. And since the return value from Console.ReadLine()
is a string, which has no direct conversion to an int, the cast fails.

Pete

so even if it returned "1" casting to int won't work?
how would one cast strings representing numbers to the number type?
thanks
mark

You can't cast from a string, even one that looks numeric, to a number.
You must use a parse function to go from string to a numeric type. In
fact, I don't believe you can cast from a string to any other datatype.
For example, to get a Guid from a string, you must call the Guid
constructor with the string.
 
Back
Top