Below is a C# program that meets your specifications. It includes a Student class with private fields, properties for accessing those fields, and a constructor with validation. Additionally, there's a TestStudent class to demonstrate the functionality and handle exceptions properly.
using System;
public class Student
{
private string firstName;
private string lastName;
private int age;
private string studentId;
private string email;
// Properties
public string FirstName
{
get { return firstName; }
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("First name cannot be null or empty.");
firstName = value;
}
}
public string LastName
{
get { return lastName; }
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("Last name cannot be null or empty.");
lastName = value;
}
}
public int Age
{
get { return age; }
set
{
if (value < 0 || value > 150)
throw new ArgumentException("Age must be between 0 and 150.");
age = value;
}
}
public string StudentId
{
get { return studentId; }
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("Student ID cannot be null or empty.");
studentId = value;
}
}
public string Email
{
get { return email; }
set
{
if (string.IsNullOrEmpty(value) || !value.Contains("@") || !value.Contains("."))
throw new ArgumentException("Invalid email format.");
email = value;
}
}
// Constructor
public Student(string firstName, string lastName, int age, string studentId, string email)
{
FirstName = firstName;
LastName = lastName;
Age = age;
StudentId = studentId;
Email = email;
}
}
public class TestStudent
{
public static void Main()
{
try
{
Student student1 = new Student("John", "Doe", 20, "S23456", "johndoe@example.com");
Console.WriteLine($"Student 1: {student1.FirstName} {student1.LastName}, Age: {student1.Age}, ID: {student1.StudentId}, Email: {student1.Email}");
// Uncomment the following line to test an error case
// Student student2 = new Student("", "Error", -1, "", "invalidEmail");
}
catch (ArgumentException ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Explanation of the Program:
-
Student Class:
- Has private fields for
firstName, lastName, age, studentId, and email.
- Has properties for each field which include validation checks within the setters.
- The constructor initializes the fields with parameters and applies validation through properties.
-
TestStudent Class:
- Demonstrates the functionality of the
Student class in a safe manner by handling potential ArgumentExceptions using a try-catch block.
- If valid, it prints the details of the
Student object.
- Includes a commented line to demonstrate triggering a validation failure (for testing purposes).
Usage:
- Run the program and observe that
Student1 successfully displays valid student information.
- Uncomment the erroneous test case line in
TestStudent class and run again to see the error handling in action.