Reputation: 18420
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.
Upvotes: 3
Views: 419
Reputation: 1062590
The (cast) syntax is very overloaded, and can perform:
"as" performs a subset of these
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.
Upvotes: 6
Reputation: 5638
If you are %100 sure that the object you want to cast will be casted, use Convert,
If not use as.
Upvotes: 1
Reputation: 11903
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.
Upvotes: 1