Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a virtual getter and abstract setter for a property?

This is essentially what I want to do:

public abstract class Uniform<T>
{
    public readonly int Location;
    private T _variable;

    public virtual T Variable
    {
        get { return _variable; }
    }
}

public class UniformMatrix4 : Uniform<Matrix4>
{
    public override Matrix4 Variable
    {
        set
        {
            _variable = value;
            GL.UniformMatrix4(Location, false, ref _variable);
        }
    }
}

The getter for Variable will be the same across all derived classes, but the setter needs to be different.

In fact... I'd prefer not to have derived classes at all (it's only one function call that will differ for each type) but I can't think of how else to do it.


Edit: If it wasn't clear what the problem I'm having is, I'm getting a syntax error:

'UniformMatrix4.Variable.set': cannot override because 'Uniform.Variable' does not have an overridable set accessor

And I'm not sure how to create an "overridable set accessor"... virtual and abstract don't seem to be allowed on the setter.

like image 855
mpen Avatar asked Dec 31 '11 22:12

mpen


1 Answers

It's not possible to do this in C#, but as a workaround you could do this. It would involve calling an abstract setter function which could be overridden by derived classes, while leaving the standard get intact. Would this work?

public abstract class Uniform<T>
{
    public readonly int Location;
    protected T _variable;

    public T Variable
    {
        get { return _variable; }
        set { SetVariable(value); } 
    }

    protected abstract void SetVariable(T value);
}

public class UniformMatrix4 : Uniform<Matrix4>
{
    public override void SetVariable(Matrix4x4 value)
    {
        _variable = value;
        GL.UniformMatrix4(Location, false, ref _variable);
    }
}
like image 105
Dr. Andrew Burnett-Thompson Avatar answered Nov 14 '22 22:11

Dr. Andrew Burnett-Thompson