Thuta Learning
C#
ProjectsProgrammingBeginner

Project: Contact Book – Part 3 (Validation + Polish)

C#Lesson 3130 min

What you'll walk away with

  • Explain the core concept and runtime behavior of Project: Contact Book – Part 3 (Validation + Polish)
  • Test normal, boundary, and invalid cases independently
  • Write readable, type-safe, and testable C# code

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.

Mental model
  1. project requirements
  2. components, state, and services
  3. tested UI

Explain the core concept and runtime behavior of Project: Contact Book – Part 3 (Validation + Polish)

Core syntax or pattern

csharp
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

  1. project requirementsclass InvalidContactException : Exception

    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.

  2. components, state, and servicesConsole.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.

  3. tested UI// }

    Test JSON persistence with valid, missing, empty, and malformed files and verify that data survives restart.

Execution flow
  1. project requirements
  2. components, state, and services
  3. 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

csharp
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 should see
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
csharp
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

What best describes the core idea of Project: Contact Book – Part 3 (Validation + Polish)?

Quick quiz 2 / 3

Which mistake should you avoid first?

Quick quiz 3 / 3

How should this be applied in a real project?

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

Easy traps

  • Hiding every exception behind a generic UI result makes debugging difficult and can conceal data loss.
  • Assuming one successful happy path proves the code is correct, maintainable, and production-ready.

Hands-on Exercise

Test JSON persistence with valid, missing, empty, and malformed files and verify that data survives restart.

You'll know it worked when: 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.

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Project: Contact Book – Part 3 (Validation + Polish) | Thuta Learning