In C# create an Election class that has number of registered voters, number of v
ID: 3871422 • Letter: I
Question
In C# create an Election class that has number of registered voters, number of votes cast, and a list of candidate names. Use properties for the first and second. For the list of candidates, create an add candidate method that accepts a string and a get candidate method that accepts an integer. For example: anElection.GetCandidate(5) gets the 5th candidate. Make each property and the GetCandidate methods do error checking.
Do error checking and throws in the Election class.
In main, test to make every throw statement in the Election class execute then, in main, catch and display appropriate messages explaining to the user of the program what happened.
Explanation / Answer
Source Code:
using System;
using System.Collections.Generic;
public class Election
{
public static int votescast{get;set;}
public static List<string> candidatenames{get;set;}
}
public class Test
{
Election obj1=new Election();
List<string> candidate=new List<string>();
public void AddCandidate()
{
Console.WriteLine("Enter Candidate Name");
candidate.Add(Console.ReadLine());
Election.votescast++;
}
public void GetCandidate(int candidateId)
{
Election.candidatenames=new List<string>();
foreach(var item in candidate)
{
Election.candidatenames.Add(item);
}
string name=Election.candidatenames[candidateId].ToString();
Console.WriteLine("Candidate Name is "+name);
Console.WriteLine("Number of votescast "+Election.votescast);
}
public static void Main()
{
Test obj=new Test();
for(int i=1;i<=2;i++)
{
obj.AddCandidate();
}
obj.GetCandidate(1);
}
}
Output: