An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
Hello @ING Docteur Bazile "Pouchon" ,
Thanks for your question.
There are many ways to handle a null entry, you can refer to these following examples. For more information, you can refer to Nullable reference types.
- Null Check (using if statement)
Console.Write("Enter your name: ");
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input))
{
Console.WriteLine("No name entered! Please provide a value.");
}
else
{
Console.WriteLine($"Hello, {input}!");
}
- Null-Coalescing Operator (??).
Returns a default value if the expression is null:
string name = null;
string result = name ?? "Default Name";
Console.WriteLine(result);
- Null-Coalescing Assignment (??=)
Assigns a value only if the variable is null:
string name = null;
name ??= "Default Name";
Console.WriteLine(name);
- Null-Conditional Operator (?.)
Safely accesses members/methods without throwing a NullReferenceException:
string name = null;
int? length = name?.Length;
Console.WriteLine(length);
string upper = name?.ToUpper()?.Trim();
- Nullable Value Types (?) Value types (like int, bool) can't be null by default. Use ? to make them nullable:
int? age = null;
if (age.HasValue)
{
Console.WriteLine($"Age: {age.Value}");
}
else
{
Console.WriteLine("Age is not provided");
}
int actualAge = age ?? 0;
- Guard Clause (Throwing on Null)
Useful for validating method parameters:
using System;
void PrintName(string name)
{
ArgumentNullException.ThrowIfNull(name); // for C# 10+
// Or for older versions:
// if (name == null) throw new ArgumentNullException(nameof(name));
Console.WriteLine(name);
}
I hope this addresses your question. If this response was helpful, please consider following the guidance to provide feedback.