I have a public class
public class Interview
{
public int InterviewId;
public string ApplicantName;
...
public List<AnsweredQuestions> AnsweredQuestions;
public Questionnaire questionnaire;
}
and use it in a main program like this:
Interview interview = new Interview();
interview.InterviewId = 1;
and a Questionnaire class
public class Questionnaire
{
public int questionnaireId;
public string outputFile;
...
}
How can I prevent modifying the attribute int the main program:
interview.questionnaire.outputFile
I found I was able to use the DocumentManager class in the main program like this:
interview = documentManager.GetInterviewSession();
interview.questionnaire = documentManager.GetQuestionnaireManagement();
interview.AnsweredQuestions = documentManager.GetInterviewAnsweredQuestions();
by using this
public class DocumentManager
{
private readonly Interview _interview;
…
public DocumentManager(Interview interview)
{
_interview = interview;
}
I’m sure I should be encapsulating, but I’m not sure how. Any help would be appreciated.
Thanks!
I’m not sure I entirely get the question, but this is the usual method for read-only encapsulation:
This creates a property named
OutputFilethat can be read publically, but only written by theQuestionnaireclass.Alternatively, you may want to use
protected set;if you want classes deriving from Questionnaire to be able to setOutputFile.