declare variable in base class that must be set in dervied class?

  • Thread starter Thread starter John B
  • Start date Start date
J

John B

I have a variable in a base class defined as:

protected Control validationControl;

How can I ensure that it is set is any dervied classes. I see that you
cannot set variables to abstract.

Thanks
 
Something like that would force the developers of any derived class to
explicitely assign value to variable i that is declared in the base
class. If they don't an assertion message box would pop up.


abstract class Base
{
protected int i = DEFAULT_I;

protected Base()
{
AssignI();
System.Diagnostics.Debug.Assert(i != DEFAULT_I, errorMessage);
System.Diagnostics.Trace.Assert(i != DEFAULT_I, errorMessage);
}

protected abstract void AssignI();

private static int DEFAULT_I = -1;
private static String errorMessage = @"You have to explicitely assign
variable 'i'";
}

class Derived : Base
{
protected override void AssignI()
{
// delete the following line and assertion will fail
i = 1;
}
}
 
Could you use an abstract Property rather than an actual variable? Let them
worry about the variable...
 
John,

1) Make sure every constructor in your base class takes a Control as a
parameter. The derived classes must call one of them.

public abstract BaseClass
{
public BaseClass(Control validationControl)
{
}
}

public class DerivedClass : BaseClass
{
public DerivedClass()
: base(GetControlSomehow())
{
}

public DerivedClass(Control validationControl)
: base(validationControl)
{
}

public Control GetControlSomehow()
{
// Do whatever it is you need to do to return a control.
}
}

2) Create a protected property or method that must be implemented in
the derived classes that returns a reference to a Control.

public abstract BaseClass
{
protected abstract ValidationControl { get; }

public void DoSomething()
{
// This line gets a reference from the derived class.
Control control = ValidationControl;
}
}

public class DerivedClass : BaseClass
{
protected override ValidationControl
{
get
{
// Return a reference to a Control.
}
}
}

These are the most common ways I do it.

Brian
 
Back
Top