0

I've seen MSDN tutorial about implicit and explicit operators. I've made some tests and it works very well.

I know the difference between them (syntaxily speaking), but I do not know the best way to use them.

My question could have been : "What kind of convertions must be done using a cast?"

For now, I just haven't overriden implicit when the result can be null..

Example:

struct TypeRef
{
    // If TypeRef is constructed with a type, will reference the given type.
    // If TypeRef is constructed with a string, will be the result of 'Type.GetType(theString)' (if the type doesn't exist: null)
    public readonly Type TypeIfExists;

    // If TypeRef is constructed with a type, will be the result of theType.Name
    // If TypeRef is constructed with a string, will reference this string.
    public readonly string TypeName;

    // Can be constructed by a string or a Type.
    // Can be converted from a string or a Type implicitely and explicitely
    // Can be converted to a string implicitely and explicitely
    // Can be converted to a Type explicitely only
}

TypeRef tr1 = "SomeType";
TypeRef tr2 = typeof(SomeType);
TypeRef tr3 = "ThisTypeDoesntExist";
Type t1 = (Type)tr1;
Type t2 = (Type)tr3; // Will be null.
string s1 = (string)tr1;
string s2 = tr1;

Thank you :)


Edit: Asked the the question more clearly :p

SylafrsOne
  • 59
  • 5

1 Answers1

0

I don't think there is a technical reason, more of an "API" reason.

From the MSDN article on explicit (emphasis mine):

The explicit keyword declares a user-defined type conversion operator that must be invoked with a cast

So if you want the users of your class to be able to convert without a cast, don't overide explicit. There are arguments about casting and readability I guess.

MattDuFeu
  • 1,615
  • 4
  • 16
  • 25
  • My question is (in fact): "When should we force users to use a cast? When can we allow users to convert without the cast?" or.. "What kind of convertions **must** be done with a cast?" (I've edited the question, it will be clearer :) ) – SylafrsOne Apr 20 '15 at 13:03
  • I'm not aware of technical reasons. Just personal preference or "standards", e.g. losing precision needs a cast to make sure the programmer is aware of the risk. – MattDuFeu Apr 20 '15 at 20:17