blackbee's picture

assign Vector to own Struct

hi there. I have a question. I want to do something like that:

mystruct x = new Vector2(0.0f, 0.0f);

and there is no problem:

struct mystruct
{
   public float x,y;
   public static implicit operator mystruct(Vector2 vec2)
   {
	mystruct newVert = new mystruct();
	newVert.x = vec2.X;
	newVert.y = vec2.Y;
	return newVert;
   }
}

but what if I want an array:

struct mystruct
{
   public float x,y;
   public static implicit operator mystruct[](Vector2[] vec2)
   {
	mystruct[] newVert = new mystruct[vec2.Length];
        for( int i=0; i<vec2.Length; i++ )
        {
	newVert[i].x = vec2[i].X;
	newVert[i].y = vec2[i].Y;
        }
	return newVert;
   }
}

I'm getting an error Error "User-defined conversion must convert to or from the enclosing type" in "implicit operator mystruct[]". Any ideas?


Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
the Fiddler's picture

Conversion operators must convert to/from the enclosing type. MyStruct and MyStruct[] are not the same types, hence the error.

A possible workaround is to use an extension method:

using System.Core;
 
public static class MyStructExtensions
{
    public static MyStruct[] ToMyStruct(this Vector2[] vec2)
    {
         // This works the same as your code
         return vec2.Select(v => new MyStruct() { X = v.X, Y = v.Y });
    }
}

which can then be used as:

Vector2[] foo = new Vector2[100];
MyStruct[] bar = foo.ToMyStruct();
blackbee's picture

I don't quite understand those lines. You are defining a method ToMyStruct in MyStructExtensions but you invoke it for Vector type. And that vec2.Select method. I don't have it in my openTK, so I cant even test and see how it works.

the Fiddler's picture
blackbee wrote:

I don't quite understand those lines. You are defining a method ToMyStruct in MyStructExtensions but you invoke it for Vector type. And that vec2.Select method. I don't have it in my openTK, so I cant even test and see how it works.

You need to compile for .Net 3.5, reference System.Core.dll and add "using System.Core; for the Select method to appear. Read c2woody's link on extension methods for more information.

blackbee's picture

Thanks for the link. I read it and now I understand those lines, but I cannot make it work for some reason. But it's not something I need for my work, it was only a test to see if it can be done. BTW in VS2010 even in .Net 3.5 you cannot add System.Core reference (it's automatically referenced... even without need to type using System.Core) , insteed I used System.Linq.

the Fiddler's picture

You are right, the namespace is System.Linq not System.Core.