tags:

views:

207

answers:

5

Introduction

I am aware that "user-defined conversions to or from a base class are not allowed". MSDN gives, as an explanation to this rule, "You do not need this operator."

I do understand that an user-defined conversion to a base class is not needed, as this obviously done implicitly. However, I do need a conversion from a base class.

In my current design, a wrapper of unmanaged code, I use a pointer, stored in an Entity class. All the classes using a pointer derive from that Entity class, for example, a Body class.

I therefore have:

Method A

class Entity
{
    IntPtr Pointer;

    Entity(IntPtr pointer)
    {
        this.Pointer = pointer;
    }
}

class Body : Entity
{
    Body(IntPtr pointer) : base(pointer) { }

    explicit operator Body(Entity e)
    {
        return new Body(e.Pointer);
    }
}

This cast is the illegal one. (Note that I didn't bother writing the accessors). Without it, the compiler will allow me to do:

Method B

(Body)myEntity
...

However, at runtime, I will get an exception saying this cast is impossible.

Conclusion

Therefore here I am, needing an user-defined conversion from a base class, and C# refuses it to me. Using method A, the compiler will complain but the code would logically work at runtime. Using method B, the compiler will not complain but the code will obviously fail at runtime.

What I find strange in this situation is that MSDN tells me I do not need this operator, and the compiler acts as if it was possible implicitly (method B). What am I supposed to do?

I am aware that I can use:

Solution A

class Body : Entity
{
    Body(IntPtr pointer) : base(pointer) { }

    static Body FromEntity(Entity e)
    {
        return new Body(e.Pointer);
    }
}

Solution B

class Body : Entity
{
    Body(IntPtr pointer) : base(pointer) { }

    Body(Entity e) : base(e.Pointer) { }
}

Solution C

class Entity
{
    IntPtr Pointer;

    Entity(IntPtr pointer)
    {
        this.Pointer = pointer;
    }

    Body ToBody()
    {
        return new Body(this.Pointer);
    }
}

But honestly, all the syntaxes for these are horrible and should in fact be casts. So, any way to make the casts work? Is it a C# design flaw or did I miss a possibility? It's as if C# didn't trust me enough to write my own base-to-child conversion using their cast system.

+5  A: 

You should use your Solution B (the constructor argument); firstly, here's why not to use the other proposed solutions:

  • Solution A is merely a wrapper for Solution B;
  • Solution C is just wrong (why should a base class know how to convert itself to any subclass?)

Also, if the Body class were to contain additional properties, what should these be initialized to when you perform your cast? It's far better to use the constructor and initialize the subclass's properties as is convention in OO languages.

robyaw
+1 for the last argument. I'll consider it. But no way of doing it as a proper cast?
Lazlo
I have no problem with a base class knowing how to convert itself to a particular subclass... especially virtually. Witness Object.ToString, and the extension methods IEnumerable.ToList, IEnumerable.ToArray.
Jon Skeet
+2  A: 

Well, when you are casting Entity to Body, you are not really casting one to another, but rather casting the IntPtr to a new entity.

Why not create an explicit conversion operator from IntPtr?

public class Entity {
    public IntPtr Pointer;

    public Entity(IntPtr pointer) {
        this.Pointer = pointer;
    }
}

public class Body : Entity {
    Body(IntPtr pointer) : base(pointer) { }

    public static explicit operator Body(IntPtr ptr) {
        return new Body(ptr);
    }

    public static void Test() {
        Entity e = new Entity(new IntPtr());
        Body body = (Body)e.Pointer;
    }
}
Igor Zevaka
Best alternative so far, will pick it if the bounty doesn't yield any other valuable result.
Lazlo
A: 

The reason you can't do it is because it's not safe in the general case. Consider the possibilities. If you want to be able to do this because the base and derived class are interchangeable, then you really only have one class and you should merge the two. If you want to have your cast operator for the convenience of being able to downcast base to derived, then you have to consider that not every variable typed as the base class will point to an instance of the specific derived class you are trying to cast it to. It might be that way, but you would have to check first, or risk an invalid cast exception. That's why downcasting is generally frowned upon and this is nothing more than downcasting in drag. I suggest you rethink your design.

siride
In my current wrapping context, the cast should be possible. I understand that in any other case, where you do not wrap an object defined as a pointer, downcasting is not recommended.
Lazlo
I still can't think of a reason why you wouldn't just combine the classes if they really are the same. But if you insist, I'd say the best option is to have an explicit function GetEntityFromBody() or similar that will return an Entity object given a Body object. That makes it clear that you are doing something out of the ordinary, while still letting you do it. Casting should not be abused.
siride
+3  A: 

It's not a design flaw. Here's why:

Entity entity = new Body();
Body body = (Body) entity;

If you were allowed to write your own user-defined conversion here, there would be two valid conversions: an attempt to just do a normal cast (which is a reference conversion, preserving identity) and your user-defined conversion.

Which should be used? Would you really want is so that these would do different things?

// Reference conversion: preserves identity
Object entity = new Body();
Body body = (Body) entity;

// User-defined conversion: creates new instance
Entity entity = new Body();
Body body = (Body) entity;

Yuk! That way madness lies, IMO. Don't forget that the compiler decides this at compile-time, based only on the compile-time types of the expressions involved.

Personally I'd go with solution C - and possibly even make it a virtual method. That way Body could override it to just return this, if you want it to be identity preserving where possible but creating a new object where necessary.

Jon Skeet
You didn't understand my intention - I do not want to cast Body to Entity, that would be horrible.I want to case Entity to Body. The thing is that I cannot know which class it is because I am only wrapping an unmanaged pointer.
Lazlo
@Lazlo: Sorry, I *did* understand your intention - I just messed up the code examples. (The variable types were right, it was just the casts that were wrong. I've fixed those now.) The reasoning behind my post remains the same, however. You want a custom conversion where there's already an explicit built-in conversion. The *clearest* way to express that desire is with a method.
Jon Skeet
(The constructor call would also be acceptable, but in some cases that can lead to less fluent code.)
Jon Skeet
@Jon: I am 200% for the existing conversion - only, it will crash at runtime. Feel free to try it yourself.
Lazlo
@Lazlo: You mean with an InvalidCastException? Yes, of course it will. That's the point - why disguise a new, very different conversion as if it were a completely different kind of conversion?
Jon Skeet
Extending on this good answer, I'd definetely vote for option C. It resembles discriminated unions (or composites). They are far more common and not used as much as they should be, you see them in System.Expression and F# has built-in support for them. @Jon: Maybe expand on this aspect?
Johannes Rudolph
@Johannes: I'm not sure I'd be able to do much more in terms of expanding... feel free to edit my post to add it in yourself though, maybe making it CW...
Jon Skeet
A: 

How about:

public class Entity {...}

public class Body : Entity
{
  public Body(Entity sourceEntity) { this.Pointer = sourceEntity.Pointer; }
}

so in code you don't have to write:

Body someBody = new Body(previouslyUnknownEntity.Pointer);

but you can use

Body someBody = new Body(previouslyUnknownEntity);

instead.

It's just a cosmetic change, I know, but it is pretty clear and you can change the internals easily. It's also used in a wrapper pattern that I can't remember a name of (for slightly diff. purposes).
It's also clear you are creating a new entity from a provided one so should not be confusing as an operator/conversion would be.

Note: haven't used a compiler so possibility of a typo is there.

Jaroslav Jandek