简体   繁体   中英

Diference between myData as string, (string) myData and Convert.ToString(myData)

I was a little curious to know that what is the difference between using as keyword , Casting or using Convert.To_______() function.

I after little searching i have found that the as operator only performs reference conversions and boxing conversions. What other differences are there.

I have also noticed that as keyword is very rarely used why is it so. Does any one of them has a performance benefit over other or are they just Redundancy in the Framework.

The (cast) syntax is very overloaded, and can perform:

  • boxing/unboxing
  • reference-preserving type casts
  • conversion operators defined on the types
  • inbuilt primitive conversions
  • Nullable-of-T wrapping/unwrapping

"as" performs a subset of these

  • reference-preserving type casts
  • some limited boxing of nullable-of-T

But the important feature here is that it doubles as an exception-free test of a type relationship - more efficient than having an exception or testing with reflection. In particular, for example:

// is it a list?
IList list = obj as IList
if(list != null) {
    // specific code for lists
}

If you strongly believe that an object is something, a (cast) is preferred as this acts as an assertion of your belief. An exception (in that case) would be desirable.

The Convert methods handle a different range of scenarios including string conversions (otherwise available via things like static .Parse methods)

If anything, it is Convert that I use least. The (cast) and "as" syntax is in very regular use.

casting vs as: casting throws in exception, as returns null if the conversion cannot be made. No performance difference whatsoever.

Convert: entirely different. You can't cast a number to a string, but you can convert is. Read the docs on what the Convert class is capable of.

If you are %100 sure that the object you want to cast will be casted, use Convert,

If not use as.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM