views:

127

answers:

3

I have (for example) an object of type A that I want to be able to cast to type B (similar to how you can cast an int to a float)

Data types A and B are my own.

Is it possible to define the rules by which this casting occurs?

Example

int a = 1;
float b = (float)a;
int c = (int)b;
+14  A: 

Yes, this is possible using C# operator overloading. There are two versions explicit and implicit.

Here is a full example:

class Program
{
    static void Main(string[] args)
    {
        A a1 = new A(1);
        B b1 = a1;

        B b2 = new B(1.1);
        A a2 = (A)b2;
    }
}

class A
{
    public int Foo;

    public A(int foo)
    {
        this.Foo = foo;
    }

    public static implicit operator B(A a)
    {
        return new B(a.Foo);
    }
}

class B
{
    public double Bar;

    public B(double bar)
    {
        this.Bar = bar;
    }

    public static explicit operator A(B b)
    {
        return new A((int)b.Bar);
    }
}

Type A can be cast implicitly to type B but type B must be cast explicitly to type A.

Daniel Renshaw
+4  A: 

Assuming you want that to be an explcit operation you'll need to write an explicit cast operator like so:

public static explicit operator MyTypeOne(MyTypeTwo i)
{
    // code to convert from MyTypeTwo to MyTypeOne
}

You can then use it like so:

MyTypeOne a = new MyTypeOne();
MyTypeTwo b = (MyTypeTwo)a;

I'd question whether you want to actually cast one type to another, or whether you actually want to convert instead. I'd say you should avoid writing cast operators for conversions, if you are just aiming to take advantage of a nice syntax :)

Also, in general it is advised not to use implicit casts, as they allow for unintended type converstions. From MSDN documentation on implicit:

However, because implicit conversions can occur without the programmer's specifying them, care must be taken to prevent unpleasant surprises. In general, implicit conversion operators should never throw exceptions and never lose information so that they can be used safely without the programmer's awareness.

MPritch
A: 

You cant overload the cast operator in c# but you can use explicit and implicit conversion operators instead:

"Using Conversion Operators (C# Programming Guide)"

Russell Troywest