Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensure property can't return null [closed]

Is that possible in C# to know from MSDN docs that some method/property/field can or can NOT return null value?

e.g. Image.RawFormat Property from MSDN says:

The ImageFormat that represents the file format of this Image.

Can it return null? Should I perform such null check in my code or it ALWAYS be not null?

like image 313
Michael Z Avatar asked Dec 27 '11 09:12

Michael Z


People also ask

How do you stop returning null in Java?

Use Null Object Design Pattern Another way to avoid returning null is to use a Null object design pattern. A null object is an object without behavior like a stub that a developer can return to the caller instead of returning null value.

Why you should not return null?

The rationale behind not returning null is that you do not have to check for it and hence your code does not need to follow a different path based on the return value. You might want to check out the Null Object Pattern which provides more information on this.

What to do instead of returning null?

Several alternatives for returning null values include using null object reference types, a null object pattern, and a result type as the return type. Therefore, the recommendation is to return an empty value instead of a null to keep the code clean and error-free.

Which of the following methods will return null if object Cannot be found?

1) all input the method is valid, in which case you must return null when the object is not found. IF and ONLY IF you provide both methods of the 2nd contract, you are allowed to throw an exception is nothing is found! Save this answer.


1 Answers

I believe that for any input value (i.e. not provided by your code) you should perform validation checks. Even if you see in MSDN that it can't return null now, it may change in the future and it's a good practice anyway.

like image 70
Roee Gavirel Avatar answered Oct 02 '22 05:10

Roee Gavirel