user4093832
user4093832

Reputation:

Cast one class object to other class object

I have two classes A and B and I want to cast an instance of A to B. What's the best way? How Can I make a utility class to perform this task?

public class A
{}
public class B
{}

Upvotes: 1

Views: 907

Answers (1)

Rob
Rob

Reputation: 45761

A good place to start is by reviewing the MSDN documentation on Casting and Type Conversions.

As there's no direct relationship between the two classes, you'll need to write a Conversion Operator. For example:

public class A
{
    public int AValue { get; set; }
}

public class B
{
    public int BValue { get; set; }

    public static explicit operator B(A instanceOfA)
    {
        return new B { BValue = instanceOfA.AValue };
    }
}

You could then write:

A instanceOfA = new A { AValue = 7 };
B instanceOfB = (B)instanceOfA;

// Will output "7"
Console.WriteLine(instanceOfB.BValue);

The documentation I've derived this example from is on MSDN, Using Conversion Operators.

If there was a direct relationship between the two classes, for example B derives from A, for example:

public class A
{
    public int Value { get; set; }
}

public class B : A
{
    public string OtherValueSpecificToB { get; set; }
}

You wouldn't then need any extra code if you wanted to cast from B to A:

B instanceOfB = new B { OtherValueSpecificToB = "b", Value = 3 };
A instanceOfBCastToA = (A)instanceOfB;

// Will output "3";
Console.WriteLine(instanceOfBCastToA.Value);
// Will not compile as when being treated as an "A" there is no "OtherValueSpecificToB" property
Console.WriteLine(instanceOfBCastToA.OtherValueSpecificToB);

Upvotes: 3

Related Questions