.NET How to explicit listing with an "how" to another (internally) from (someType) someobject and why?

I understand that when you use an explicit cast like this:

(someType)someobject 

you may get an invalid cast exception if someobject is actually not someType .

I also understand that by pressing as as follows:

 myObject = someObject as someType 

myObject just displays null if someobject not really someType .

How are they evaluated differently and why?

+8
casting explicit c #
source share
2 answers

John Skeet has C # faq , where he explains the differences between the two operators. See โ€œWhat is the difference between using syntax and as operator?โ€

Quote:

Using the as operator differs from distinguishing in C # in three important ways:

  • It returns zero when the variable you are trying to convert is not of the requested type or its inheritance chain instead of throwing an exception.
  • It can only be applied to variables of a reference type converted to reference types.
  • Use because it will not perform custom conversions, such as implicit or explicit conversions of statements to do.

In fact, there are two completely different operations defined in IL that process these two keywords (castclass and isinst) - this is not just โ€œsyntactic sugarโ€ written by C # to get this behavior. The as statement seems to be slightly faster in v1.0 and v1.1 of the Microsoft CLR compared to casting (even in cases where there are no invalid casts that have much lower casting performance due to an exception).

+7
source share

Years passed ... but minutes ago I came across a practical example, which I think is worth noting - the difference between the two:

Check this:

 class Program { static void Main(string[] args) { Console.WriteLine(GenericCaster<string>(12345)); Console.WriteLine(GenericCaster<object>(new { a = 100, b = "string" }) ?? "null"); Console.WriteLine(GenericCaster<double>(20.4)); //prints: //12345 //null //20.4 Console.WriteLine(GenericCaster2<string>(12345)); Console.WriteLine(GenericCaster2<object>(new { a = 100, b = "string" }) ?? "null"); //will not compile -> 20.4 does not comply due to the type constraint "T : class" //Console.WriteLine(GenericCaster2<double>(20.4)); /* * Bottom line: GenericCaster2 will not work with struct types. GenericCaster will. */ } static T GenericCaster<T>(object value, T defaultValue = default(T)) { T castedValue; try { castedValue = (T) Convert.ChangeType(value, typeof(T)); } catch (Exception) { castedValue = defaultValue; } return castedValue; } static T GenericCaster2<T>(object value, T defaultValue = default(T)) where T : class { T castedValue; try { castedValue = Convert.ChangeType(value, typeof(T)) as T; } catch (Exception) { castedValue = defaultValue; } return castedValue; } } 

Bottom line: GenericCaster2 will not work with structures. GenericCaster will be.

0
source share

All Articles