Reputation: 20464
When implementing the CType
operator in a custom Type like this one below, the Type is not casteable using DirectCast
operator:
Public Structure ColorInfo
...
Public Shared Widening Operator CType(ByVal colorInfo As ColorInfo) As Color
Return Color.FromArgb(colorInfo.R, colorInfo.G, colorInfo.B)
End Operator
...
End Structure
On the other hand it is directly assignable to a Color
object, which is very confussing:
Dim obj As color = MyColorInfo
Then, I would like to implement the DirectCast
operator firstly to obtain typing comfort in my environment (instead of using the CType
) and secondly to obtain the beneffits, if any, of what explains the MSDN docs here:
DirectCast does not use the Visual Basic run-time helper routines for conversion, so it can provide somewhat better performance than CType when converting to and from data type Object.
How I can implement it in C# or Vb.Net?.
Upvotes: 1
Views: 1145
Reputation: 5477
DirectCast
is a 'compile-time' cast with added type-checking at runtime. It's meant for casting when type inheritance or interface implementation are in play.
It will not consider user defined casts, such as you have here, so it's not applicable.
CType
is appropriate and you should just use that, rather than trying to subvert the language. It will look for user defined conversions and apply them.
Performance-wise, the CType
is as good as it gets here. Because the types are known at compile time in your example, you'll get the optimal code for it.
To address the comment: The principal thing is that you, as a programmer, do nothing for DirectCast
, VB.NET does everything. In fact, you can't do anything to get a DirectCast
other than starting your class with implementing a particular interface or inheriting from a base class.
If you want to provide any other conversions, then you use CType
. This is a fundamental split between the two. DirectCast
comes automatically and you can't modify its behaviour. CType
will allow you to extend its behaviour by providing custom conversions.
So to summarise: either your class inherits from a type, in which case DirectCast
of an instance to and from that base type works, or it doesn't, in which case you need to create your own CType
override.
Upvotes: 2