K
KShvats
Hey there
Which is better: "(inSet as ICloneable).Clone()" or
"((ICloneable)inSet).Clone()"?
Thank you
Which is better: "(inSet as ICloneable).Clone()" or
"((ICloneable)inSet).Clone()"?
Thank you
David said:So you just get a different
kind of exception in that case than if you'd just done a straight cast.
David Anton said:Neither.
If inSet is not IClonable, then both alternatives will result in an
exception (null.Clone() will also throw an exception).
For this case, you'd be better off to do:
IClonable foo = inSet as IClonable;
foo.Clone();
Jon Shemitz said:To elaborate a bit on this, the straight cast will give you an
exception that says that your inSet does not support IClonable. Pretty
straightforward. The `as` cast will give you a null-dereference
exception, which means you'd have to look at the code and translate a
null-dereference to "Oh, inSet does not support IClonable."
KShvats said:"Casting impact and performance in C#
I'll try here to discuss the difference between the two types of casting.
C# provides two ways for casting object references
object myClass = new MyClass();
((MyClass)myClass).MyMethod();
This is an example of downcasting (casting from the top to the bottom of
the class hierarchy).
In the first line of code, the compiler emits a "Castclass" opcode, which
converts the reference to the type specified between the parenthesis if
possible (if not, an InvalidCastException exception is thrown).
The second case is :
object myClass = new MyClass();
(myClass as MyClass).MyMethod();
here we use the as operator , which works much faster, because it only
checks the reference type but doesn't perform any sort of cast (nor throws
any exception).
In performance terms, it is better to use the second option, because it
speeds up much more the code execution, avoiding type casts and exception
throwing."
http://msdonet.blogspot.com/
KShvats said:object myClass = new MyClass();
((MyClass)myClass).MyMethod();
In the first line of code, the compiler emits a "Castclass" opcode,
which converts the reference to the type specified between the
parenthesis if possible (if not, an InvalidCastException exception is
thrown).
object myClass = new MyClass();
(myClass as MyClass).MyMethod();
here we use the as operator , which works much faster, because it only
checks the reference type but doesn't perform any sort of cast (nor
throws any exception).
In performance terms, it is better to use the second option, because it
speeds up much more the code execution, avoiding type casts and
exception throwing."