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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With