Skip to content

Instantly share code, notes, and snippets.

@a-patel
Last active July 14, 2023 14:35
Show Gist options
  • Save a-patel/a2e05c85d64253f6b91c00cdb4c5e775 to your computer and use it in GitHub Desktop.
Save a-patel/a2e05c85d64253f6b91c00cdb4c5e775 to your computer and use it in GitHub Desktop.
C#.NET - Null Conditional (or Safe Navigation) Operator (?.) and (?[]) Example
/* Example-1 */
// Without null conditional or safe navigation operator
string name;
int? length;
if (name != null)
{
length = name.Length;
}
else
{
length = null;
}
// With null conditional or safe navigation operator
int? length = name?.Length;
/* Example-2 */
void DisplayPerson(Person person)
{
Console.WriteLine(person?.FirstName);
Console.WriteLine(person?.LastName);
}
/* Example-3 */
var name = person?[3]?.FirstName;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment