Antediluvian
Antediluvian

Reputation: 723

C# type cast from my type to my other type

My code gets an object with everything in it. And as per different needs, it needs to be cast to different individual type.

class A
{
    public static explicit operator B (A value)
    {
        ....
        return new B();
    }
}

class B
{
    ...
}

public static T Get<T>(...)
{
    A a = new A();
    return (T)A;
}

var b = Get<B>(...); // cannot convert a type of A to B

Any ideas?

Upvotes: 0

Views: 228

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500525

You can't do this, as the compiler doesn't know (and there's no way to tell it) that there's a conversion from A to T. You'd need to constrain T in some way to indicate that, and you just can't do that - in the same way that you can't constrain T to have a + operator etc. (The C# team has been considering how what that might look like and how it might be implemented, but it's definitely not available at the moment.)

You need a way of telling the compiler how to convert from an A to a T - you could add a parameter to Get to tell it that:

public static T Get<T>(Func<A, T> converter)
{
    A a = new A();
    return converter(a);
}

You'd then call it with:

var b = Get<B>(a => (B) a);

for example.

Upvotes: 4

Mark Z.
Mark Z.

Reputation: 2447

C# doesn't support duck typing, but you could serialize your class A into a json string, then deserialize it into class B, any any properties that have the exact same names and types (or via a mapping you set up using JSON attributes or JSON settings) will make their way into class B as desired.

Upvotes: -1

Related Questions