How to stop .First crashing if it finds nothing?

my code is:

public Tweak thickness{ get{ return tweak.First(t=> t.type == TweakType.thickness); } }

and the error is:

NullReferenceException: Object reference not set to an instance of an object
Element.<get_thickness>m__4 (.Tweak t) (at Assets/scripts/Element.cs:25)

I completely understand the problem. Its a null reference exception because it cannot find any “Tweak” objects fitting the conditions specified. In this case, I want my code to return “null” rather than crash. I tried a few different ways of doing it but get the same result. Can I do a null check somehow without actually causing a null reference exception? And then return null if its not there?

Most likely the variable “tweak” is null. Also, you can use .FirstOrDefault which returns null if it doesn’t find anything (but you still need for the variable tweak to be an object (not null)).