Visibility and Accessibility Modifiers

SurveyBuilder Corner

Our example application, SurveyBullder builds on the concepts we've discussed in this tutorial. Using a combination of access and structural modifiers allows us to design our classes with encapsulation in mind.

Question

The Question type is an example where we have applied these modifiers to control how this class can be used. Here is the implementation.

public abstract class Question
{
    public string Label { get; set; }
    
    public Answer Ask()
    {
        PrintQuestion();
        
        while (true)
        {
            var input = Console.ReadLine();
            string errorMessage;
            if (!ValidateInput(input, out errorMessage))
            {
                Console.WriteLine(errorMessage);
                Console.WriteLine("Please, correct your input.");
                continue;
            }
            
            return CreateAnswer(input);
        }
    }
    
    protected virtual void PrintQuestion()
    {
        Console.WriteLine(Label);
    }
    
    
    protected abstract bool ValidateInput(string input, out string errorMessage);
    protected abstract Answer CreateAnswer(string validInput);
}

The Question class is marked as public and abstract. If you refer back to their usages you'll remember that public means it is accessible to all callers. The abstract modifier means that we can't create an instance of the Question class directly, we have to derive a subclass of Question.

Take a look at this method:

protected virtual void PrintQuestion()
{
    Console.WriteLine(Label);
}

Because this method is protected, it means it is only accessible from within the Question class itself, and any class that derives from Question. The method is also marked as virtual, which means we can provide a default implementation, which can optionally be overriden in a derived class.

Alternatively, here is another method:

protected abstract bool ValidateInput(string input, out string errorMessage);

This method is marked as abstract. This means it must be overridden in a derived class.

Page 16 of 18