Recap - Null Safety
Part of the Logic & Flow section of Coddy's C# journey — lesson 35 of 66.
Challenge
EasyCreate a method called SafelyProcessData that takes two parameters:
- A string
namethat could be null - A nullable int
age
The method should:
- Check if
nameis null or empty using appropriate null checking patterns - Check if
agehas a value - Return a formatted string as follows:
- If
nameis null, return "No name provided" - If
nameis empty or whitespace, return "Invalid name" - If
ageis null, return "Name: [name], Age: Unknown" - Otherwise, return "Name: [name], Age: [age]"
- If
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
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety