Casting

Published on Sunday, December 24, 2023

Casting

Only use "as" when you are not sure if the cast will succeed and you are going to check the result against null, otherwise you confuse the linter.

Don’t: πŸ™

Cat cat = objectThatMightBeACat as Cat; // cat might be null
cat.Meow();

Better: 😐

Cat cat = objectThatMightBeACat as Cat;
cat?.Meow();

Best: πŸ™‚

if (objectThatMightBeACat is Cat cat)
	cat.Meow();

If you are sure of the type (an exception will be thrown if you are wrong), use the direct cast:

(Cat)objectThatImSureIsACat.Meow();

Be aware of the different intentions of LINQ selectors. Use _First _when there may be more than one matching Item; _FirstOrDefault _when there may be more than one, or possibly none. Use _Single _when there is supposed to be one and only one matching item, and _SingleOrDefault _when there is either one or none.

When using the _XXXOrDefault _variants, be sure to check for null.