Is there a way to treat integers eg. 3
and 5
as their own types with an additional property being the value they represent? Specifically I want Modulo<3>
to be different to Modulo<5>
to prevent them being used together in an operation that operates on multiple Modulo<T>
s.
I’ll explain my use case, please excuse me if this is not mathematically sound but I think it illustrates my point well.
public interface IBase
{
static abstract int Base { get; }
}
public class FiveBase : IBase
{
public static int Base { get; } = 5;
}
public class SevenBase : IBase
{
public static int Base { get; } = 7;
}
public class ModuloHardcoded<T> where T : IBase
{
int value;
public ModuloHardcoded(int value)
{
this.value = value;
}
public ModuloHardcoded<T> Add(ModuloHardcoded<T> other)
{
return new ModuloHardcoded<T>((value + other.value) % T.Base);
}
}
The above code allows us to create ModuloHardcoded
objects with a specific integer base. While all ModuloHardcoded
objects have access to the same methods and properties, they can only interact with other objects with the same type T
the same way List<string>
and List<int>
are distinct. The problem with the above approach is that it requires a new class for every supported base, while I want to support all integer bases by default. Ideally I want something similar to below.
// T will be an integer here
public class Modulo<T>
{
int value;
public Modulo(int value)
{
this.value = value;
}
// The below is not possible since T is a type and not an int
public Modulo<T> Add(Modulo<T> other)
{
return new Modulo<T>((value + other.value) % T);
}
}
I am aware from this question that something similar is possible in cpp, and not possible in C#, but I have tried to provide more context showing where such a feature might be wanted. How can I achieve compile time type safety, preventing me from adding two incompatible objects? I understand that I can just add fields and properties and perform runtime checks but I feel like a solution leveraging type checking would be more elegant. Is my whole premise flawed, maybe there is a simpler way to implement the desired behaviour.
Mukund Srinivasan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3