Skip to content

Instantly share code, notes, and snippets.

@mattkenefick
Created July 31, 2021 17:51
Show Gist options
  • Save mattkenefick/4089df4a2b8b36a062d64c577055a204 to your computer and use it in GitHub Desktop.
Save mattkenefick/4089df4a2b8b36a062d64c577055a204 to your computer and use it in GitHub Desktop.
Snippets in C#: More ways to check for NULL
// Option B: Checks if is NOT null
if (dog?.breed is { }) return dog.breed;
// Option C: Checks if is NOT null, then assigns to local variable "breedA"
if (dog?.breed is { } breedA) return breedA;
// Option D: Uses property pattern to check on object and return props as variables
if (dog?.breed is { Length: var lengthA } breedB) return $"{breedB} ({lengthA} characters long)";
public class Dog
{
public string breed { get; set; }
}
public class Dog
{
public string breed { get; set; }
}
public class Program
{
public static void Main()
{
TestNull();
TestNotNull();
}
static void TestNull()
{
Dog dog = new Dog();
string breed = GetBreed(dog);
Console.WriteLine("TestNull: " + breed);
}
static void TestNotNull()
{
Dog dog = new Dog { breed = "american pitbull" };
string breed = GetBreed(dog);
Console.WriteLine("TestNull: " + breed);
}
static string GetBreed(Dog? dog)
{
// Option A: Checks if is null
// if (dog?.breed is null) return "unknown";
// Option B: Checks if is NOT null
// if (dog?.breed is { }) return dog.breed;
// Option C: Checks if is NOT null, then assigns to local variable "breedA"
// if (dog?.breed is { } breedA) return breedA;
// Option D: Uses property pattern to check on object and return props as variables
// if (dog?.breed is { Length: var lengthA } breedB) return $"{breedB} ({lengthA} characters long)";
// Option E: Property pattern as one-liner
return dog?.breed is { Length: var lengthB } breedC
? $"`{breedC}` ({lengthB} characters long)"
: "Unknown Breed";
// Unreachable Code
// return dog.breed;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment