Reputation: 351
I was working on a small project in C# (actually, moved for few weeks to .Net) and I came across the following situation,
str = System.Convert.ToString(
(sheetRange.Cells[rcnt, ccnt] as Excel.Range).Value2);
In the above code, I was trying to read from an excel sheet onto a String. Initially , I tried doing the following,
str = (string) ((sheetRange.Cells[rcnt, ccnt] as Excel.Range).Value2);
Which resulted in a runtime error stating , Unable to cast object of type 'System.Double' to type 'System.String'. InValidException was caught.
I googled out to find out the difference between the two, but couldn't get much. I am kind of tangled with this. So my questions are the following,
1) What is the difference between the two, rather to be more specific, what is the difference between an explicit typecast and using system.convert? Does this apply for all the types?
2) Is this is the same in Java, if it is what is the equivalent of it?
I updated to show what exactly I am getting while I cast it with string. I am getting exception while I cast a Double to a string. But, converting Double to a string Works. Now my question is why it isn't allowing to cast a double to a string while it allows to convert the double to a string. I hope I am making myself clear.
Please pardon me if its a simple one and if I had over looked some basic points about type casting.
Thanks in advance.
Upvotes: 0
Views: 1029
Reputation:
In answer to the first part of your question: Casting and Converting are two different things. I'm not a Java developer, but I would suspect it's the same in Java.
MSDN has an article which answers this in detail: Casting and Type Conversions (C# Programming Guide)
Upvotes: 4