Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast one compound custom type to another

Tags:

c#

I'm trying to write a converter class for custom types--converting one type (and all of its properties) to another type that has matching properties.

The problem comes in when the property is also a custom type, rather that a simple type.
The custom types are all identical, except they live in different namespaces in the same solution.
TypeTwo objects are Webservice references.

For example

public TypeOne ConvertToTypeTwo (TypeTwo typeTwo)
{
var typeOne = new TypeOne();
typeOne.property1 = typeTwo.property1; //no problem on simple types
typeOne.SubType = typeTwo.SubType; //problem!
...
}

The error I get on the line above is:

Error 166 Cannot implicitly convert type 'TypeTwo.SubType' to 'TypeOne.SubType'

I've tried casting like so

typeOne.SubType = (TypeOne)typeTwo.SubType;

But get:

Error 167 Cannot convert type 'TypeTwo.SubType' to 'TypeOne.SubType'

And like so

typeOne.SubType = typeTwo.SubType as TypeOne;   

But get:

Error 168 Cannot convert type 'TypeTwo.SubType' to 'TypeOne.SubType' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

I'm not sure what other options I have, or if I'm just doing something fundamentally wrong. Any thoughts?

like image 214
Forty-Two Avatar asked May 24 '12 16:05

Forty-Two


2 Answers

If the two subtypes are different types, you'll have to write a separate converter to convert between the two types.

For example:

public TypeOne ConvertToTypeTwo (TypeTwo typeTwo)
{
    var typeOne = new TypeOne();
    typeOne.property1 = typeTwo.property1; //no problem on simple types
    typeOne.SubType = ConvertToTypeTwo(typeTwo.SubType); //problem!
}

public TypeOneSubtype ConvertToTypeTwo(TypeTwoSubType typeTwo)
{
    var subOne = new TypeOneSubType;
    subOne.property1 = typeTwo.property1;
    // etc.
}
like image 167
Randolpho Avatar answered Nov 04 '22 17:11

Randolpho


You can't do that. Even if the two types have exactly the same layout (same fields with same types), you cannot cast from one to another. It's impossible.

What you have to do instead is to create a converter (either as method, a separate class or a cast operator) that can translate from a type to another.

like image 25
user703016 Avatar answered Nov 04 '22 16:11

user703016