Re: InvalidCastException
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Wed, 20 Jul 2005 17:35:40 +0100
Mrinal Kamboj <mrinal.kamboj@xxxxxxxxxx> wrote:
> Way it goes is :
>
> InvalidCastException is thrown only when tried between types which are
> possible to typecast for e.g:
>
> string s = "1" ;
> int i = (int) s ; // Compiler Error
>
> Object s = "1" ;
> int i = (int) s ; // Invalid Cast Exception
>
> so even if you do something like :
>
> int j = 1 ;
> object s = j.toString() ;
> int i = (int) s ; // Invalid Cast Exception
>
> so , invariably at runtime what is inside an object type is unknown ,
> till the point it applies the typecasting logic and try to map it to
> given data type , when it leads to exception .
Yes, but I believe what the OP is trying to say is that the exception
could say what the actual type was, like it does in Java. Consider the
following two programs:
Java:
public class Test
{
public static void main (String[] args)
{
try
{
Object o = new Object();
String s = (String)o;
}
catch (Exception e)
{
System.out.println(e);
}
}
}
C#:
using System;
public class Test
{
public static void Main (String[] args)
{
try
{
Object o = new Object();
String s = (String)o;
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
Results (with stack traces removed):
Java:
java.lang.ClassCastException: java.lang.Object
C# (with .NET 1.1):
System.InvalidCastException: Specified cast is not valid.
C# (with .NET 2.0 beta):
System.InvalidCastException: Unable to cast object of type
'System.Object' to type 'System.String'.
So it seems that .NET 1.1 is the worst offender, giving you no
information at all about the types involved. Java is somewhat better
telling you what you were trying to cast, but not what you were trying
to cast it to. .NET 2.0 is the best of the bunch, telling you both
types involved.
--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
.
- Follow-Ups:
- Re: InvalidCastException
- From: cody
- Re: InvalidCastException
- References:
- InvalidCastException
- From: cody
- Re: InvalidCastException
- From: Scott M.
- Re: InvalidCastException
- From: cody
- Re: InvalidCastException
- From: Matthijs van der Vleuten
- Re: InvalidCastException
- From: Mrinal Kamboj
- InvalidCastException
- Prev by Date: Re: InvalidCastException
- Next by Date: Question school
- Previous by thread: Re: InvalidCastException
- Next by thread: Re: InvalidCastException
- Index(es):
Relevant Pages
|