C# Object-Oriented Programming: CSV Parsing and Inheritance
Posted on May 31, 2026 in Computer Engineering
CSV Data Processing in C#
public class Program
{
public static void Main(string[] args)
{
List<Employee> employees = new List<Employee>();
string filePath = "employees.csv";
try
{
using(StreamReader reader = new StreamReader(filePath))
{
reader.ReadLine(); // Skip header
string line;
while((line = reader.ReadLine()) != null)
{
string[] data = line.Split(',');
int id = int.Parse(data[0]);
string type = data[1];
string name = data[2];
double salary = double.Parse(data[3]);
string specificData = data[4];
Employee employee = null;
if(type == "Temporary")
{
employee = new TemporaryEmployee { Id = id, Name = name, BaseSalary = salary, ContractEndDate = specificData };
}
else if(type == "Permanent")
{
employee = new PermanentEmployee { Id = id, Name = name, BaseSalary = salary, YearsOfService = int.Parse(specificData) };
}
employees.Add(employee);
}
}
}
catch (FileNotFoundException) { Console.WriteLine($"Error: file {filePath} not found."); }
catch (IOException ex) { Console.WriteLine($"I/O Error: {ex.Message}"); }
catch (FormatException) { Console.WriteLine("Error: Invalid data format."); }
catch (Exception ex) { Console.WriteLine($"Unexpected error: {ex.Message}"); }
}
}
OOP Concepts: Interfaces and Abstract Classes
- Interfaces: Define a contract of methods that implementing classes must provide.
- Abstract Classes: Define shared attributes and behavior for subclasses.
Code Implementation
public interface IWeapon
{
void Repair(int materialUnits);
int GetWeaponStatus();
}
public abstract class Character
{
private string name;
protected int health;
private string city;
public Character(string name, string city) { this.name = name; this.city = city; }
public string GetName() => name;
public int GetHealth() => health;
public string GetCity() => city;
public abstract int Attack();
public abstract void TakeDamage(int amount);
}
public class Hoplite : Character, IWeapon
{
private int shieldDurability;
public Hoplite(string name, string city) : base(name, city)
{
this.shieldDurability = 12;
this.health = 76;
}
public override int Attack()
{
Random rand = new Random();
return rand.Next(5, 13);
}
public override void TakeDamage(int amount)
{
if (shieldDurability > 0)
{
shieldDurability = Math.Max(0, shieldDurability - 3);
health = Math.Max(0, health - (amount - 2));
}
else { health = Math.Max(0, health - amount); }
}
public void Repair(int materialUnits) => shieldDurability += materialUnits;
public int GetWeaponStatus() => shieldDurability;
}