ok so i want to make a generic class that will change the value of a datatype. The reason i want to do this is so i can have undo and redo methods. I could write a class for each valuetype i need. I.E. double, int... but it would be much easier if i could create a generic class to do this.
This is what i have
class CommandChangeDouble : Command
{
    double _previous;
    double _new;
    double* _objectRef;
    public unsafe CommandChangeDouble(double* o, double to)
    {
        _objectRef = o;
        _previous = *o;
        _new = to;
        *_objectRef = _new;
    }
    public unsafe void Undo()
    {
        *_objectRef = _previous;
    }
    public unsafe void Redo()
    {
        *_objectRef = _new;
    }
}
this is what i want
class CommandChangeValue<T> : Command
{
    T _previous;
    T _new;
    T* _objectRef;
    public unsafe CommandChangeValue(T* o, T to)
    {
        _objectRef = o;
        _previous = *o;
        _new = to;
        *_objectRef = _new;
    }
    public unsafe void Undo()
    {
        *_objectRef = _previous;
    }
    public unsafe void Redo()
    {
        *_objectRef = _new;
    }
}
but this gives me the error Error "Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')"
Is there a better way to do this or a way to get around this error?
C# 7.3 solved that issue with new generic constraint - unmanaged.
Basically it allows to do something like that:
void Hash<T>(T value) where T : unmanaged
{
    // Okay
    fixed (T* p = &value) 
    { 
        ...
    }
}
Docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With