(Question at the bottom)
I have a class which I need to be used like:
float [] floatArray=new float[1024];
Foo<float> var1=floatArray; // creates foo, assigns the array to a field
var1.compute();
and
Foo<float> floatArray2 = new Foo<float>(1024);
Foo<float> var2=floatArray2; // creates foo, copies its internal array
var2.compute();
Then I thought I could use two implicit conversions, one for arrays, one for non-arrays.
I could manage to do first version with:
public static implicit operator Foo<T> (T[] b)
{
if (typeof(T) == typeof(int) ||
typeof(T) == typeof(uint) ||
typeof(T) == typeof(byte) ||
typeof(T) == typeof(char) ||
typeof(T) == typeof(double) ||
typeof(T) == typeof(long) ||
typeof(T) == typeof(float))
{
Foo<T> foo = new Foo<T>();
foo.arr = b;
return foo;
}
else
{
throw new NotImplementedException();
}
}
but this has a lot of checks in it and I tried to add constraint in class declaration like:
public class Foo<T> where T:typeof(float),typeof(int)
{
...
}
but it made the compiler complain as "int is not a valid constraint".
In the second case, I needed to exclude arrays, I tried this:
public static implicit operator Foo<T> (Foo<T> b)
{
Foo<T> foo = new Foo<T>();
foo.arr = b.arr;
return foo;
}
but this time compiler says "cant take enclosing type and convert to enclosing type" and underlines operator Foo<T>
.
But these actually work:
public static implicit operator Foo<T> (Foo<float> b)
public static implicit operator Foo<float> (Foo<T> b)
and I don't want to cross-convert int
type to float
nor float
to int
. Just T
to same T
(not all T to all T).
Question: How to constrain the implicit conversion to only arrays of primitive numbers like float,byte,double,long,int and 1-2 custom classes without adding too many typechecks in the method body(custom classes are generic with float int byte...)? (where keyword doesn't work on method <T>
definition)
Foo already implements IList but IList could be anything like a Bar[]
right? So I can't use interface to narrow the search I assume. Also I don't want the =
to do a reference assignment for Foo
, but create a new one(or just use the current, would be better) and copy its internal array, just like a struct, but still have many advantages of a class(inheritance, ...).