Make sure the property cannot return null

Is it possible in C # to know from MSDN documents that some method / property / property may or may not return null ?

eg. Image.RawFormat Property from MSDN says:

ImageFormat, which represents the file format of this image.

Can it return null? Should I do such a null check in my code, or is it ALWAYS not null?

+6
source share
4 answers

I believe that for any input value (i.e. not provided by your code) you should perform validation checks. Even if you see on MSDN that it cannot return null now, it may change in the future, and in any case this is good practice.

+4
source

I don't think there is a guaranteed way in the documentation, but you can usually say if it can be null. For example, if you look at the documentation for System.Windows.Documents.Inline.NextInline , it says:

An Inline object representing the next Inline that is peer to this element or null if there is no next Inline.

Regardless if your program cannot handle null and you have an instance of a reference type, you should still do the appropriate check for null .

+1
source

Resharper will warn you when you use an object that cannot be proved non-null (for example, by looking at the NotNull attribute or seeing that the called method makes its own checks), and then unobtrusively offers you to add a check with a click or two.

This way you can avoid clogging your code with checks where it is not needed.

In addition, often using Debug.Assert is enough to perform "unlikely but-what-if" checks (where you should complete whatever the code does anyway).

+1
source

There is no way to verify that a type with a null type will not return null , however, consider that the structure is stable in terms of code changes. I will strive to make an informed decision by looking at how the property or method you invoke works using ILSpy or JustDecompile .

In your example, it would turn out that null cannot be returned, since the constructor for ImageFormat takes a Guid and assigns it to a private field.

Depending on what you are doing with this property, it is worth checking:

  • That a StatusException not StatusException to access the property.
  • That ImageFormat is equal to the format you expect, since it can be an image format that neither GdiPlus nor .NET are aware of.
0
source

Source: https://habr.com/ru/post/904522/


All Articles