Value types of variable size

Posted by YellPika on Stack Overflow See other posts from Stack Overflow or by YellPika
Published on 2011-01-05T02:28:25Z Indexed on 2011/01/05 2:54 UTC
Read the original article Hit count: 149

Filed under:
|
|

I'm trying to code a small math library in C#. I wanted to create a generic vector structure where the user could define the element type (int, long, float, double, etc.) and dimensions.

My first attempt was something like this...

public struct Vector<T>
{
    public readonly int Dimensions;
    public readonly T[] Elements;

    // etc...
}

Unfortunately, Elements, being an array, is also a reference type. Thus, doing this,

Vector<int> a = ...;
Vector<int> b = a;
a[0] = 1;
b[0] = 2;

would result in both a[0] and b[0] equaling 2.

My second attempt was to define an interface IVector<T>, and then use Reflection.Emit to automatically generate the appropriate type at runtime. The resulting classes would look roughly like this:

public struct Int32Vector3 : IVector<T>
{
    public int Element0;
    public int Element1;
    public int Element2;

    public int Dimensions { get { return 3; } }

    // etc...
}

This seemed fine until I found out that interfaces seem to act like references to the underlying object. If I passed an IVector to a function, and changes to the elements in the function would be reflected in the original vector.

What I think is my problem here is that I need to be able to create classes that have a user specified number of fields. I can't use arrays, and I can't use inheritance.

Does anyone have a solution?

EDIT: This library is going to be used in performance critical situations, so reference types are not an option.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET