0

I have little peace of code:

private static void Casting<T>(T obj)
{
    String str = (String)obj; //Error
    str = obj as String;
}

Line String str = (String)obj returns me compile-time error

"Error CS0030 Cannot convert type 'T' to 'string'"

Lets say, I agree with the error. But why second line do not same behavior? So my question is - why "as" do not generate the error, while casting do?

zzfima
  • 1,528
  • 1
  • 14
  • 21

2 Answers2

2

When using as, if a cast is not possible, null is returned instead of throwing an exception like a 'normal' cast would do.

See : https://msdn.microsoft.com/en-us/library/cscsdfbt.aspx

Tom C.
  • 593
  • 4
  • 12
  • i am not talking about runtime. I am talking about compile time – zzfima Jun 26 '15 at 07:41
  • @zzfima - Compile time is the exact same answer, because `as` can handle it, there is no need to invent warnings/errors about something the developer probably already knows – Sayse Jun 26 '15 at 07:53
1

By using (String)obj you say to compiler "Hey I am absolutely sure that this type can be converted to a string - just do it!" where in as operator - it's when you allow compiler to do it's job and say 'please try to convert it for me if it's possible'...

Something like this :D

Searock
  • 6,278
  • 11
  • 62
  • 98
Fabjan
  • 13,506
  • 4
  • 25
  • 52