tags:

views:

72

answers:

2

I have a generic class,

class ComputeScalar<T> : IComputeVariable where T : struct
{
   // This is why i have to use generics.
   ComputeBuffer<T> buffer;

   T data;
}

class ComputeArray<T> : IComputeVariable where T : struct
{
   // This is why i have to use generics.
   ComputeBuffer<T> buffer;

   T[] data;
}

and i use this class in a list in another class,

class SomeClass
{
   List<IComputeVariable> variables;
}

I created the interface because in C# we can't use generic classes for type parameters. (Right?) What i want to learn is how can i make "data" a member of interface? And during runtime how can i determine type of data? (Data can be any ValueType)

+4  A: 

You could only make data a member of the interface by making it weakly typed as object:

public interface IComputeVariable
{
    object Data { get; }
}

(Note that it has to be a property - you can't specify fields in interfaces.)

You'd then probably want to implement that explicitly in ComputeScalar<T>, to avoid the weakly typed version from being used where the strongly typed version was available.

An alternative would be to make the interface generic, and SomeClass too:

class SomeClass<T> where T : struct
{
   List<IComputeVariable<T>> variables;
}

We don't really know enough about your situation to know which is the right approach, but those are two of your options.

Jon Skeet
The buffer is used for sending data to gpu and has to be generic. So second alternative is not an option because there are different types of variable i need to send to gpu. List has to be generic. But i ll try first one.thank you very much.
Kayhano
First one works for me, thank you :)
Kayhano
+1  A: 
interface IComputeVariable<T> where T : struct
{
  T Data { get; }
}

class ComputeScalar<T> : IComputeVariable<T> where T : struct
{
   // This is why i have to use generics.
   ComputeBuffer<T> buffer;

   public T Data {get; set; }
}
Mike