C# Programming Assessments - Questions with Answers
C# Assessment Bank (Q&A)
Beginner → Intermediate
C# / OOP / Collections
Exceptions
Q1
Find Items (SortedDictionary)
Given: public static SortedDictionary<String, long> itemDetails (already provided in template).
| Method | Description |
|---|---|
FindItemDetails(long soldCount) |
Return matching item(s) whose sold count equals soldCount. If not found return empty dictionary and print Invalid sold count in Main. |
FindMinandMaxSoldItems() |
Return a List<string> where index 0 = minimum sold item name, index 1 = maximum sold item name. |
SortByCount() |
Return all items sorted in ascending order by sold count (value). |
Main Flow: Get values from user → call methods → print results. If result is empty where specified, print the exact message.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
// In your template this is already provided.
public static SortedDictionary<string, long> itemDetails = new SortedDictionary<string, long>()
{
{ "Pen", 120 },
{ "Pencil", 80 },
{ "Notebook", 250 },
{ "Eraser", 60 }
};
// 1) Find items by sold count (value)
public SortedDictionary<string, long> FindItemDetails(long soldCount)
{
var result = new SortedDictionary<string, long>();
foreach (var kv in itemDetails)
{
if (kv.Value == soldCount)
result[kv.Key] = kv.Value;
}
return result; // empty dictionary if not found
}
// 2) Find min and max sold item names (min first, max second)
public List<string> FindMinandMaxSoldItems()
{
var result = new List<string>();
if (itemDetails.Count == 0) return result;
var min = itemDetails.OrderBy(kv => kv.Value).First();
var max = itemDetails.OrderByDescending(kv => kv.Value).First();
result.Add(min.Key);
result.Add(max.Key);
return result;
}
// 3) Sort all items by sold count and return as Dictionary
public Dictionary<string, long> SortByCount()
{
return itemDetails
.OrderBy(kv => kv.Value)
.ToDictionary(kv => kv.Key, kv => kv.Value);
}
// Sample Main to test
public static void Main()
{
Program p = new Program();
Console.Write("Enter sold count to search: ");
long soldCount = long.Parse(Console.ReadLine());
var found = p.FindItemDetails(soldCount);
if (found.Count == 0)
{
Console.WriteLine("Invalid sold count");
}
else
{
foreach (var kv in found)
Console.WriteLine($"{kv.Key} : {kv.Value}");
}
var minMax = p.FindMinandMaxSoldItems();
if (minMax.Count >= 2)
Console.WriteLine($"Min Sold Item: {minMax[0]}, Max Sold Item: {minMax[1]}");
Console.WriteLine("Sorted by sold count:");
var sorted = p.SortByCount();
foreach (var kv in sorted)
Console.WriteLine($"{kv.Key} : {kv.Value}");
}
}
Q2
Movie Stock (List<Movie>)
| Property | Type |
|---|---|
| Title | string |
| Artist | string |
| Genre | string |
| Ratings | int |
| Method | Description |
|---|---|
AddMovie(string movieDetails) |
Input format: Title,Artist,Genre,Ratings. Convert to Movie and add to MovieList. |
ViewMoviesByGenre(string genre) |
Return movies matching genre. If none, return empty list and print No Movies found in genre '{genre}' in Main. |
ViewMoviesByRatings() |
Sort by Ratings ascending and return list. |
using System;
using System.Collections.Generic;
using System.Linq;
public class Movie
{
public string Title { get; set; }
public string Artist { get; set; }
public string Genre { get; set; }
public int Ratings { get; set; }
}
public class Program
{
// In your template this is already provided.
public static List<Movie> MovieList = new List<Movie>();
public void AddMovie(string movieDetails)
{
// Expected: Title,Artist,Genre,Ratings
string[] parts = movieDetails.Split(',');
Movie m = new Movie
{
Title = parts[0].Trim(),
Artist = parts[1].Trim(),
Genre = parts[2].Trim(),
Ratings = int.Parse(parts[3].Trim())
};
MovieList.Add(m);
}
public List<Movie> ViewMoviesByGenre(string genre)
{
// If your evaluation is strictly case-sensitive, replace OrdinalIgnoreCase with Ordinal.
return MovieList
.Where(m => m.Genre.Equals(genre, StringComparison.OrdinalIgnoreCase))
.ToList();
}
public List<Movie> ViewMoviesByRatings()
{
return MovieList
.OrderBy(m => m.Ratings)
.ToList();
}
public static void Main()
{
Program p = new Program();
Console.Write("Enter number of movies: ");
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
Console.WriteLine("Enter movie details (Title,Artist,Genre,Ratings):");
p.AddMovie(Console.ReadLine());
}
Console.Write("Enter genre to search: ");
string g = Console.ReadLine();
var byGenre = p.ViewMoviesByGenre(g);
if (byGenre.Count == 0)
{
Console.WriteLine($"No Movies found in genre '{g}'");
}
else
{
Console.WriteLine("Movies by Genre:");
foreach (var m in byGenre)
Console.WriteLine($"{m.Title} | {m.Artist} | {m.Genre} | {m.Ratings}");
}
Console.WriteLine("Movies sorted by Ratings:");
var sorted = p.ViewMoviesByRatings();
foreach (var m in sorted)
Console.WriteLine($"{m.Title} | {m.Artist} | {m.Genre} | {m.Ratings}");
}
}
Q3
Calculate Numbers (GPA + Grade)
| Method | Description |
|---|---|
AddNumbers(int numbers) | Add the number to NumberList. |
GetGPAScored() |
GPA = ((n1*3)+(n2*3)+...+(nk*3)) / (count*3). If list is empty return -1 and print No Numbers Available.
|
GetGradeScored(double gpa) |
Return grade using the GPA table. If GPA < 5 or > 10 return '\0' and print Invalid GPA. |
| GPA | Grade |
|---|---|
| Equal to 10 | S |
| >= 9 and < 10 | A |
| >= 8 and < 9 | B |
| >= 7 and < 8 | C |
| >= 6 and < 7 | D |
| >= 5 and < 6 | E |
using System;
using System.Collections.Generic;
public class Program
{
// In your template this is already provided.
public static List<int> NumberList = new List<int>();
public void AddNumbers(int numbers)
{
NumberList.Add(numbers);
}
public double GetGPAScored()
{
if (NumberList.Count == 0) return -1;
// GPA formula in the question (credit point = 3)
double sum = 0;
foreach (int n in NumberList)
sum += (n * 3);
double gpa = sum / (NumberList.Count * 3);
return gpa;
}
public char GetGradeScored(double gpa)
{
if (gpa < 5 || gpa > 10) return '\0';
if (gpa == 10) return 'S';
if (gpa >= 9) return 'A';
if (gpa >= 8) return 'B';
if (gpa >= 7) return 'C';
if (gpa >= 6) return 'D';
return 'E';
}
public static void Main()
{
Program p = new Program();
Console.Write("Enter how many numbers: ");
int count = int.Parse(Console.ReadLine());
for (int i = 0; i < count; i++)
{
Console.Write($"Enter number {i + 1}: ");
p.AddNumbers(int.Parse(Console.ReadLine()));
}
double gpa = p.GetGPAScored();
if (gpa == -1)
{
Console.WriteLine("No Numbers Available");
return;
}
Console.WriteLine($"GPA: {gpa}");
char grade = p.GetGradeScored(gpa);
if (grade == '\0')
Console.WriteLine("Invalid GPA");
else
Console.WriteLine($"Grade: {grade}");
}
}
Q4
Yoga Meditation (BMI + Fees)
Properties (MeditationCenter): MemberId, Age, Weight, Height, Goal, BMI
| Datatype | Property |
|---|---|
| int | MemberId |
| int | Age |
| double | Weight |
| double | Height |
| string | Goal |
| double | BMI |
BMI Formula: BMI = Weight(Kgs) / (Height(In) * Height(In)) (BMI must be in 2 decimal places, hint: Math.Floor)
| Goal | BMI Condition | Fee |
|---|---|---|
| Weight Loss | BMI >= 25 && BMI < 30 | 2000 |
| Weight Loss | BMI >= 30 && BMI < 35 | 2500 |
| Weight Loss | BMI >= 35 | 3000 |
| Weight Gain | Any | 2500 |
using System;
using System.Collections;
using System.Collections.Generic;
public class MeditationCenter
{
public int MemberId { get; set; }
public int Age { get; set; }
public double Weight { get; set; } // Kgs (as per question text)
public double Height { get; set; } // Inches (as per question text)
public string Goal { get; set; } // "Weight Loss" or "Weight Gain"
public double BMI { get; set; }
}
public class Program
{
// In your template this is already provided.
public static ArrayList memberList = new ArrayList();
public void AddYogaMember(int memberId, int age, double weight, double height, string goal)
{
MeditationCenter m = new MeditationCenter
{
MemberId = memberId,
Age = age,
Weight = weight,
Height = height,
Goal = goal,
BMI = 0
};
memberList.Add(m);
}
public double CalculateBMI(int memberId)
{
foreach (MeditationCenter m in memberList)
{
if (m.MemberId == memberId)
{
double bmi = m.Weight / (m.Height * m.Height);
// 2 decimal places using Math.Floor (truncate)
bmi = Math.Floor(bmi * 100) / 100;
m.BMI = bmi;
return bmi;
}
}
return 0; // not present
}
public int CalculateYogaFee(int memberId)
{
foreach (MeditationCenter m in memberList)
{
if (m.MemberId == memberId)
{
// Ensure BMI is calculated
if (m.BMI == 0)
CalculateBMI(memberId);
if (m.Goal == "Weight Gain")
return 2500;
if (m.Goal == "Weight Loss")
{
if (m.BMI >= 25 && m.BMI < 30) return 2000;
if (m.BMI >= 30 && m.BMI < 35) return 2500;
if (m.BMI >= 35) return 3000;
}
return 0; // for any other goal
}
}
return 0; // member not found
}
public static void Main()
{
Program p = new Program();
// Add a few sample members
p.AddYogaMember(101, 26, 78, 68, "Weight Loss");
p.AddYogaMember(102, 30, 55, 64, "Weight Gain");
Console.Write("Enter MemberId to calculate BMI: ");
int id = int.Parse(Console.ReadLine());
double bmi = p.CalculateBMI(id);
if (bmi == 0)
{
Console.WriteLine($"MemberId '{id}' is not present");
return;
}
Console.WriteLine($"BMI: {bmi}");
int fee = p.CalculateYogaFee(id);
Console.WriteLine($"Yoga Fee: {fee}");
}
}
Q5
Ecommerce Application (Custom Exception)
| Class | Properties |
|---|---|
| EcommerceShop | string UserName, double WalletBalance, double TotalPurchaseAmount |
| Method | Description |
|---|---|
MakePayment(string name, double balance, double amount) |
Create and return object. If balance < amount, throw InsufficientWalletBalanceException with message Insufficient balance in your digital wallet. |
Main: If payment is valid, print Payment successful. Otherwise catch exception and print the exception message. Output is case-sensitive.
using System;
public class EcommerceShop
{
public string UserName { get; set; }
public double WalletBalance { get; set; }
public double TotalPurchaseAmount { get; set; }
}
public class InsufficientWalletBalanceException : Exception
{
public InsufficientWalletBalanceException(string message) : base(message) { }
}
public class Program
{
public EcommerceShop MakePayment(string name, double balance, double amount)
{
if (balance < amount)
throw new InsufficientWalletBalanceException("Insufficient balance in your digital wallet");
// Create object and return it
return new EcommerceShop
{
UserName = name,
WalletBalance = balance - amount, // remaining balance (realistic)
TotalPurchaseAmount = amount
};
}
public static void Main()
{
Program p = new Program();
Console.Write("Enter user name: ");
string name = Console.ReadLine();
Console.Write("Enter wallet balance: ");
double balance = double.Parse(Console.ReadLine());
Console.Write("Enter purchase amount: ");
double amount = double.Parse(Console.ReadLine());
try
{
EcommerceShop shop = p.MakePayment(name, balance, amount);
Console.WriteLine("Payment successful");
}
catch (InsufficientWalletBalanceException ex)
{
Console.WriteLine(ex.Message);
}
}
}
Q6
User Authentication (Password Mismatch Exception)
| Class | Properties |
|---|---|
| User | string Name, string Password, string ConfirmationPassword |
| Method | Description |
|---|---|
ValidatePassword(string name, string password, string confirmationPassword) |
If password != confirmationPassword (case-sensitive), throw PasswordMismatchException with message Password entered does not match. |
Main: If valid user object is returned, print Registered Successfully. Else catch exception and print message.
using System;
public class User
{
public string Name { get; set; }
public string Password { get; set; }
public string ConfirmationPassword { get; set; }
}
public class PasswordMismatchException : Exception
{
public PasswordMismatchException(string message) : base(message) { }
}
public class Program
{
public User ValidatePassword(string name, string password, string confirmationPassword)
{
if (!password.Equals(confirmationPassword, StringComparison.Ordinal)) // case-sensitive
throw new PasswordMismatchException("Password entered does not match");
return new User
{
Name = name,
Password = password,
ConfirmationPassword = confirmationPassword
};
}
public static void Main()
{
Program p = new Program();
Console.Write("Enter name: ");
string name = Console.ReadLine();
Console.Write("Enter password: ");
string pass = Console.ReadLine();
Console.Write("Confirm password: ");
string confirm = Console.ReadLine();
try
{
User u = p.ValidatePassword(name, pass, confirm);
Console.WriteLine("Registered Successfully");
}
catch (PasswordMismatchException ex)
{
Console.WriteLine(ex.Message);
}
}
}
Q7
Construction Estimate (Validation Exception)
| Class | Properties |
|---|---|
| EstimateDetails | float ConstructionArea, float SiteArea |
| Method | Description |
|---|---|
ValidateConstructionEstimate(float constructionArea, float siteArea) |
If constructionArea ≤ siteArea → return object. If constructionArea > siteArea → throw ConstructionEstimateException with message Sorry your Construction Estimate is not approved. |
using System;
public class EstimateDetails
{
public float ConstructionArea { get; set; }
public float SiteArea { get; set; }
}
public class ConstructionEstimateException : Exception
{
public ConstructionEstimateException(string message) : base(message) { }
}
public class Program
{
public EstimateDetails ValidateConstructionEstimate(float constructionArea, float siteArea)
{
if (constructionArea <= siteArea)
{
return new EstimateDetails
{
ConstructionArea = constructionArea,
SiteArea = siteArea
};
}
throw new ConstructionEstimateException("Sorry your Construction Estimate is not approved");
}
public static void Main()
{
Program p = new Program();
Console.Write("Enter Construction Area: ");
float cArea = float.Parse(Console.ReadLine());
Console.Write("Enter Site Area: ");
float sArea = float.Parse(Console.ReadLine());
try
{
EstimateDetails ed = p.ValidateConstructionEstimate(cArea, sArea);
Console.WriteLine("Construction Estimate Approved");
}
catch (ConstructionEstimateException ex)
{
Console.WriteLine(ex.Message);
}
}
}
Q8
User Verification (Phone Number Validation)
| Class | Properties |
|---|---|
| User | string Name, string PhoneNumber |
| Method | Description |
|---|---|
ValidatePhoneNumber(string name, string phoneNumber) |
If phoneNumber length == 10 → return user object. Else throw InvalidPhoneNumberException with message Invalid phone number. |
using System;
public class User
{
public string Name { get; set; }
public string PhoneNumber { get; set; }
}
public class InvalidPhoneNumberException : Exception
{
public InvalidPhoneNumberException(string message) : base(message) { }
}
public class Program
{
public User ValidatePhoneNumber(string name, string phoneNumber)
{
if (phoneNumber != null && phoneNumber.Length == 10)
{
return new User
{
Name = name,
PhoneNumber = phoneNumber
};
}
throw new InvalidPhoneNumberException("Invalid phone number");
}
public static void Main()
{
Program p = new Program();
Console.Write("Enter name: ");
string name = Console.ReadLine();
Console.Write("Enter phone number: ");
string phone = Console.ReadLine();
try
{
User u = p.ValidatePhoneNumber(name, phone);
Console.WriteLine("User Verified");
}
catch (InvalidPhoneNumberException ex)
{
Console.WriteLine(ex.Message);
}
}
}
Content for the important practical questions will appear here.