c# - How to implement the DirectCast operator in a type? -
when implementing ctype
operator in custom type 1 below, type not casteable using directcast
operator:
public structure colorinfo ... public shared widening operator ctype(byval colorinfo colorinfo) color return color.fromargb(colorinfo.r, colorinfo.g, colorinfo.b) end operator ... end structure
on other hand directly assignable color
object, confussing:
dim obj color = mycolorinfo
then, implement directcast
operator firstly obtain typing comfort in environment (instead of using ctype
) , secondly obtain beneffits, if any, of explains msdn docs here:
directcast not use visual basic run-time helper routines conversion, can provide better performance ctype when converting , data type object.
how can implement in c# or vb.net?.
directcast
'compile-time' cast added type-checking @ runtime. it's meant casting when type inheritance or interface implementation in play. not consider user defined casts, such have here, it's not applicable.
ctype
appropriate , should use that, rather trying subvert language. user defined conversions , apply them.
performance-wise, ctype
gets here. because types known @ compile time in example, you'll optimal code it.
to address comment: principal thing you, programmer, nothing directcast
, vb.net everything. in fact, can't directcast
other starting class implementing particular interface or inheriting base class.
if want provide other conversions, use ctype
. fundamental split between two. directcast
comes automatically , can't modify behaviour. ctype
allow extend behaviour providing custom conversions.
so summarise: either class inherits type, in case directcast
of instance , base type works, or doesn't, in case need create own ctype
override.
Comments
Post a Comment