
assign Vector to own Struct
Posted Saturday, 8 May, 2010 - 15:56 by blackbee inhi 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
Re: assign Vector to own Struct
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:
which can then be used as:
Re: assign Vector to own Struct
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.
Re: assign Vector to own Struct
http://msdn.microsoft.com/en-us/library/bb383977.aspx
Re: assign Vector to own Struct
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.Re: assign Vector to own Struct
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.
Re: assign Vector to own Struct
You are right, the namespace is System.Linq not System.Core.