0

I am trying to convert an object of a class in c# to an other class. I cannot explicitly cast because of the type of fields I have inside.

Assume Class A has ID (int), Cobrand (string) and Values (class X) also Class B has ID(int), Cobrand (string) and Values (class X)

if it was just converting from ClassA to ClassB with class X inside , I would either do

 ClassA _classA = (ClassA)_classB 

or

 _classA.ID = _classB.ID;
 _classA.Cobrand = _classB.Cobrand;

Since I have a class inside these classes (even though they are same) I get an error saying "Cannot convert type ClassB.ClassX to ClassA.ClassX". How can I cast and convert this?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
challengeAccepted
  • 7,106
  • 20
  • 74
  • 105

1 Answers1

2

This is not casting problem you encountered. It is mapping problem. For this kind of problems use AutoMapper (it is common problem if you working with database+webservice infrastructure, and is commonly used practice):

using System;
using AutoMapper;

public class Foo
{
    public string A { get; set; }
    public int B { get; set; }  
}

public class Bar
{
    public string A { get; set; }
    public int B { get; set; }  
}

public class Program
{
    public static void Main()       
    {
        Mapper.CreateMap<Foo,Bar>();

        var foo = new Foo { A="test", B=100500 };

        var bar = Mapper.Map<Bar>(foo);

        Console.WriteLine("foo type is {0}", foo.GetType());
        Console.WriteLine("bar type is {0}", bar.GetType());

        Console.WriteLine("foo.A={0} foo.B={1}", foo.A, foo.B);
        Console.WriteLine("bar.A={0} bar.B={1}", bar.A, bar.B);
    }
}

PS

Actually, there exist a little hack in C#. It is possible to cast one structure to another by aligning fields in stack. Here how it can be done:

[StructLayout(LayoutKind.Explicit)]
public struct MyStructHack
{
    [FieldOffset(0)]
    public Foo a;

    [FieldOffset(0)]
    public Bar b;
}

public struct Foo { public int foo; }
public struct Bar { public int bar;}

var convert = new MyStructHack();
convert.a = new Foo {foo = 3};
var bar = convert.b;
Console.WriteLine(bar.bar);

Bear in mind that it is neccessary to have same byte orders in your structures. This techique commonly used because it is faster than doing C# casting. It just skips many language protection checks.

eocron
  • 6,885
  • 1
  • 21
  • 50