tags:

views:

105

answers:

3

Hi,

Is there any way, how to convert this:

namespace Library
{
    public struct Content
    {
        int a;
        int b;
    }
}

I have struct in Library2.Content that has data defined same way ({ int a; int b; }), but different methods.

Is there a way to convert a struct instance from Library.Content to Library2.Content? Something like:

Library.Content c1 = new Library.Content(10, 11);
Library2.Content c2 = (Libary2.Content)(c1); //this doesn't work
+8  A: 

You have several options, including:

  • You could define an explicit (or implicit) conversion operator from one type to the other. Note that this implies that one library (the one defining the conversion operator) must take a dependency on the other.
  • You could define your own utility method (possibly an extension method) that converts either type to the other. In this case, your code to do the conversion would need to change to invoke the utility method rather than performing a cast.
  • You could just new up a Library2.Content and pass in the values of your Library.Content to the constructor.

HTH,
Kent

Kent Boogaart
+3  A: 

You could define an explicit conversion operator inside Library2.Content as follows:

// explicit Library.Content to Library2.Content conversion operator
public static explicit operator Content(Library.Content content) {
    return new Library2.Content {
       a = content.a,
       b = content.b
    };
}
Bertrand Marron
Problem is, that i dont have access inside Library2 and in Library1 I dont know about exist of Library2
Perry
Then go for @Kent Boogaart's second or third option.
Bertrand Marron
+2  A: 

Just for completeness, there is another way to do this if the layout of the data types is the same - through marshaling.

static void Main(string[] args)
{

    foo1 s1 = new foo1();
    foo2 s2 = new foo2();
    s1.a = 1;
    s1.b = 2;

    s2.c = 3;
    s2.d = 4;

    object s3 = s1;
    s2 = CopyStruct<foo2>(ref s3);

}

static T CopyStruct<T>(ref object s1)
{
    GCHandle handle = GCHandle.Alloc(s1, GCHandleType.Pinned);
    T typedStruct = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
    handle.Free();
    return typedStruct;
}

struct foo1
{
    public int a;
    public int b;

    public void method1() { Console.WriteLine("foo1"); }
}

struct foo2
{
    public int c;
    public int d;

    public void method2() { Console.WriteLine("foo2"); }
}
BrokenGlass