Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Convert struct to another struct

Tags:

c#

struct

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
like image 666
Perry Avatar asked Sep 26 '10 17:09

Perry


1 Answers

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.
like image 137
Kent Boogaart Avatar answered Sep 29 '22 10:09

Kent Boogaart