Göran Andersson said:
Göran, look at this code:
public class MySpecificType { }
public class MySpecificType2 : MySpecificType { }
public class FooTester
{
public void A()
{
Version v = new Version();
Random r = new Random();
Random r2 = (Random)v;
Random r3 = v as Random;
object o = new object();
MySpecificType x = o as MySpecificType;
MySpecificType y = (MySpecificType)o;
MySpecificType x2 = o as MySpecificType2;
MySpecificType y2 = (MySpecificType2)o;
}
}
On the r2 line, C# gives this error message: "Cannot convert type
'System.Version' to 'System.Random' via a built-in conversion".
On the r3 line, C# gives this error message: "Cannot convert type
'System.Version' to 'System.Random'".
I always thought that C# would let these lines compile and give a
run-time error, but the compiler's smarter than I thought (maybe it's
something new in C# 2.0). The x line compiles but gives this run-time
error: "Unable to cast object of type 'System.Object' to type
'Console_Playground.MySpecificType'".
I think we're both right, and that it depends on whether the compiler
can figure out the type compatibility fully at compile-time or not.
You're right; I'm wrong here. I did believe that "as" would always
compile until I tried the r3 line above (at your prompting).
That's completely backwards.
Not quite, I don't think. Although to be clearer I should have said this:
"then use[STRIKE "USE"] the first syntax [ADD "CAN BE USED"]". Though
typically I would use the cast syntax. And I use this pattern all the time:
MySpecificType x = o as MySpecificType;
if (x == null)
{
// x isn't of MySpecificType or doesn't it's type doesn't derive
// from MySpecificType.
}
Sorry if I wasn't clear about that.
Assuming that Smithers means this:
MySpecificType x = someObject as MySpecificType;
MySpecificType x = (MySpecificType) someObject;
and also that Smithers means that someObject is is of type
MySepcificType or a class that derives from MySpecific type. However,
since what he posted is a little ambiguous (he doesn't specify what the
type of x is) I may well be reading his question differently than you
and/or what he means, and maybe the two assumptions I just mentioned
aren't what he intended, but that's the way I read he question. Maybe
Smithers will clarify for us.
The bottom line is the first variant (again, assuming these two
assumptions) is useful when you don't want an exception throw at
run-time and will check the variable to see if it is null or not, and
the second variant is useful when you pretty much now the type of the
variable being cast and if you don't know 100% you don't mind an
exception being thrown at run-time.