CodeBlanks Logo Icon CodeBlanks

Adding questions

C# course · Intermediate · Lesson 43/116

Learn to add questions with the AddQuestion method.

Quiz class and adding questions

In this lesson we define the Quiz class. It will hold a List<Question> of questions and an AddQuestion method to add new questions. A Count method will report how many questions there are.

List<Question> is a dynamically growing collection. Use questions.Add(q) to add a new question. The questions.Count property gives the list length. AddQuestion takes a Question from outside and adds it to the list.

Using List<Question>

List<Question> is one of C#'s generic collections. The line using System.Collections.Generic; must be at the top of the file. Declaration: private List<Question> questions = new List<Question>();.

The list starts empty. Use questions.Add(q) to append an element. The questions.Count property gives the length. The list grows its capacity automatically as needed; you don't have to set a size in advance.

Exercise Add a question and count

Add a private List<Question> questions = new List<Question>(); field, a public void AddQuestion(Question q) method and a public int Count() method to Quiz. In Main, create a Quiz, add one question and print Count.

Show example solution
Write the Quiz class as `class Quiz { private List<Question> questions = new List<Question>(); public void AddQuestion(Question q) { questions.Add(q); } public int Count() { return questions.Count; } }`. In Main write `var quiz = new Quiz(); quiz.AddQuestion(new Question { Text = "Capital?", Answer = "Ankara" }); Console.WriteLine(quiz.Count());`.
Example solution:
using System;
using System.Collections.Generic;

class Question
{
    public string Text;
    public string Answer;
}

class Quiz
{
    private List<Question> questions = new List<Question>();

    public void AddQuestion(Question q)
    {
        questions.Add(q);
    }

    public int Count()
    {
        return questions.Count;
    }
}

class Program
{
    static void Main()
    {
        var quiz = new Quiz();
        quiz.AddQuestion(new Question { Text = "Capital?", Answer = "Ankara" });
        Console.WriteLine(quiz.Count());
    }
}

Test yourself

  1. Fill in the blank: AddQuestion signature

    class Quiz
    {
        public void AddQuestion(____)
        {
            questions.Add(q);
        }
    }
    Show answer
    class Quiz
    {
        public void AddQuestion(Question q)
        {
            questions.Add(q);
        }
    }
  2. Which is suitable for storing questions in the Quiz class?

    • List<Question>
    • string
    • int
    • Question
    Show answer

    List<Question> — Correct. `List<Question>` holds many questions dynamically.

  3. Match: Quiz parts

    List<Question>
    question list
    AddQuestion
    adds a question
    Count
    question count
    new Quiz
    creates a new quiz

All lessons in Intermediate