Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i make a generic variable without using generics?

Tags:

c#

generics

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)

like image 438
Kayhano Avatar asked Apr 28 '26 02:04

Kayhano


2 Answers

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.

like image 166
Jon Skeet Avatar answered Apr 30 '26 15:04

Jon Skeet


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; }
}
like image 34
Mike Avatar answered Apr 30 '26 15:04

Mike