Explain it simply
Project: Contact Book – Part 3 (Validation + Polish), in plain language
By the end of Part 2, all the CRUD operations in the Contact Book work fine — but if the user types invalid input (an empty name, a wrong menu choice), the app can still crash. Here's where we put the exception handling (try/catch) concept from the Advanced chapter into real practice, making the app robust. We'll also use LINQ's OrderBy() to sort the contacts list by name so it displays more cleanly. Once this part is done, the Contact Book project is complete end-to-end — concepts from all three chapters (Basic, Intermediate, and Advanced) have come together in one single project.
Problem → Why → Solution
The problem — why this concept matters
Hiding every exception behind a generic UI result makes debugging difficult and can conceal data loss.
A common mistake
Assuming one successful happy path proves the code is correct, maintainable, and production-ready.
Core concept — understand how it works
Polish should add consistent validation, exception boundaries, persistence-corruption handling, logging, deterministic tests, and user-friendly messages. Make saves safer with a temporary-file and replace pattern, and keep secrets and personal data out of logs.
- project requirements
- components, state, and services
- tested UI
Explain the core concept and runtime behavior of Project: Contact Book – Part 3 (Validation + Polish)
Core syntax or pattern
class InvalidContactException : Exception
{
public InvalidContactException(string message) : base(message) { }
}
class ContactManager
{
private List<Contact> contacts = new List<Contact>();
public void AddContact(Contact c)
{
if (string.IsNullOrWhiteSpace(c.Name) || string.IsNullOrWhiteSpace(c.Phone))
{
throw new InvalidContactException("Name and Phone are required.");
}
contacts.Add(c);
}
public void ShowAll()
{
Console.WriteLine("---- Contact List (sorted) ----");
foreach (Contact c in contacts.OrderBy(c => c.Name))
{
Console.WriteLine($"{c.Name,-15} | {c.Phone,-12} | {c.Email}");
}
Console.WriteLine("--------------------------------");
}
}
// inside Main()'s Add branch
// try
// {
// manager.AddContact(new Contact { Name = name, Phone = phone, Email = email });
// Console.WriteLine("Contact added successfully.");
// }
// catch (InvalidContactException ex)
// {
// Console.WriteLine("Error: " + ex.Message);
// }Polish should add consistent validation, exception boundaries, persistence-corruption handling, logging, deterministic tests, and user-friendly messages. Make saves safer with a temporary-file and replace pattern, and keep secrets and personal data out of logs.
Read the code step by step
- project requirements
class InvalidContactException : ExceptionBy the end of Part 2, all the CRUD operations in the Contact Book work fine — but if the user types invalid input (an empty name, a wrong menu choice), the app can still crash. Here's where we put the exception handling (try/catch) concept from the Advanced chapter into real practice, making the app robust. We'll also use LINQ's OrderBy() to sort the contacts list by name so it displays more cleanly. Once this part is done, the Contact Book project is complete end-to-end — concepts from all three chapters (Basic, Intermediate, and Advanced) have come together in one single project.
- components, state, and services
Console.WriteLine("---- Contact List (sorted) ----");Polish should add consistent validation, exception boundaries, persistence-corruption handling, logging, deterministic tests, and user-friendly messages. Make saves safer with a temporary-file and replace pattern, and keep secrets and personal data out of logs.
- tested UI
// }Test JSON persistence with valid, missing, empty, and malformed files and verify that data survives restart.
- project requirements
- components, state, and services
- tested UI
Success
Explain the core concept and runtime behavior of Project: Contact Book – Part 3 (Validation + Polish)
Failure
Hiding every exception behind a generic UI result makes debugging difficult and can conceal data loss.
Let's think about this for a second
By the end of Part 2, all the CRUD operations in the Contact Book work fine — but if the user types invalid input (an empty name, a wrong menu choice), the app can still crash. Here's where we put the exception handling (try/catch) concept from the Advanced chapter into real practice, making the app robust. We'll also use LINQ's OrderBy() to sort the contacts list by name so it displays more cleanly. Once this part is done, the Contact Book project is complete end-to-end — concepts from all three chapters (Basic, Intermediate, and Advanced) have come together in one single project.
Let's build it
Write a custom exception class InvalidContactException that inherits from Exception. In the AddContact() method, throw InvalidContactException whenever Name or Phone is empty. In the Add branch of the Main() method, catch this exception with try/catch and display the error message on the console. Update the ShowAll() method to use LINQ's OrderBy(c => c.Name) so contacts are sorted alphabetically by name. Finally, polish up the output format with Console.WriteLine() calls, adding a header and separator line to make it look nicer.
Code Example
class InvalidContactException : Exception
{
public InvalidContactException(string message) : base(message) { }
}
class ContactManager
{
private List<Contact> contacts = new List<Contact>();
public void AddContact(Contact c)
{
if (string.IsNullOrWhiteSpace(c.Name) || string.IsNullOrWhiteSpace(c.Phone))
{
throw new InvalidContactException("Name and Phone are required.");
}
contacts.Add(c);
}
public void ShowAll()
{
Console.WriteLine("---- Contact List (sorted) ----");
foreach (Contact c in contacts.OrderBy(c => c.Name))
{
Console.WriteLine($"{c.Name,-15} | {c.Phone,-12} | {c.Email}");
}
Console.WriteLine("--------------------------------");
}
}
// inside Main()'s Add branch
// try
// {
// manager.AddContact(new Contact { Name = name, Phone = phone, Email = email });
// Console.WriteLine("Contact added successfully.");
// }
// catch (InvalidContactException ex)
// {
// Console.WriteLine("Error: " + ex.Message);
// }You'll end up with a fully polished Contact Book app: trying to add a contact with an empty name or phone number shows an error message instead of crashing the app, and the contact list displays neatly sorted in alphabetical order by name.5-Minute Challenge
Try validating the phone number format with a regex or a simple length check, and throw InvalidContactException again when the format is wrong.
A Quick Heads-Up
Don't just catch an exception and let it fail silently without showing a message — always tell the user what went wrong.
Real-world usage
How to apply it in a real project
Test JSON persistence with valid, missing, empty, and malformed files and verify that data survives restart.
Mini challenge
Build it yourself
Test JSON persistence with valid, missing, empty, and malformed files and verify that data survives restart.
- Rebuild the example without copying it
- Test a normal input and an edge case
- Predict the compiler or output result before running it
class InvalidContactException : Exception
{
public InvalidContactException(string message) : base(message) { }
}
class ContactManager
{
private List<Contact> contacts = new List<Contact>();
public void AddContact(Contact c)
{
if (string.IsNullOrWhiteSpace(c.Name) || string.IsNullOrWhiteSpace(c.Phone))
{
throw new InvalidContactException("Name and Phone are required.");
}
contacts.Add(c);
}
public void ShowAll()
{
Console.WriteLine("---- Contact List (sorted) ----");
foreach (Contact c in contacts.OrderBy(c => c.Name))
{
Console.WriteLine($"{c.Name,-15} | {c.Phone,-12} | {c.Email}");
}
Console.WriteLine("--------------------------------");
}
}
// inside Main()'s Add branch
// try
// {
// manager.AddContact(new Contact { Name = name, Phone = phone, Email = email });
// Console.WriteLine("Contact added successfully.");
// }
// catch (InvalidContactException ex)
// {
// Console.WriteLine("Error: " + ex.Message);
// }Expected: Explain the core concept and runtime behavior of Project: Contact Book – Part 3 (Validation + Polish)
Show hint
Test JSON persistence with valid, missing, empty, and malformed files and verify that data survives restart.
Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- project requirements → components, state, and services → tested UI
- Polish should add consistent validation, exception boundaries, persistence-corruption handling, logging, deterministic tests, and user-friendly messages. Make saves safer with a temporary-file and replace pattern, and keep secrets and personal data out of logs.
- Hiding every exception behind a generic UI result makes debugging difficult and can conceal data loss.
- Test JSON persistence with valid, missing, empty, and malformed files and verify that data survives restart.
Unit testing C# in .NET — Microsoft Learn