Menu
Coddy logo textTech

Recap - Null Safety

Part of the Logic & Flow section of Coddy's C# journey — lesson 35 of 66.

challenge icon

Challenge

Easy

Create a method called SafelyProcessData that takes two parameters:

  1. A string name that could be null
  2. A nullable int age

The method should:

  1. Check if name is null or empty using appropriate null checking patterns
  2. Check if age has a value
  3. Return a formatted string as follows:
    • If name is null, return "No name provided"
    • If name is empty or whitespace, return "Invalid name"
    • If age is null, return "Name: [name], Age: Unknown"
    • Otherwise, return "Name: [name], Age: [age]"

Make sure to use defensive programming techniques to handle all possible null scenarios!

Try it yourself

using System;

class Program
{
    // Implement the SafelyProcessData method here
    
    static void Main(string[] args)
    {
        string nameInput = Console.ReadLine();
        string ageInput = Console.ReadLine();
        
        // Handle the case where the input is the string "null"
        string name = nameInput == "null" ? null : nameInput;
        
        int? age = null;
        if (ageInput != "null")
        {
            age = int.Parse(ageInput);
        }
        
        string result = SafelyProcessData(name, age);
        Console.WriteLine(result);
    }
}

All lessons in Logic & Flow