Where to check if an object is null or not?

前端 未结 13 1488
广开言路
广开言路 2020-12-17 10:18

Where do you check if an object that you are passing to a method is null or not?

Should an object need to be tested before calling a method? or within the method tha

13条回答
  •  情话喂你
    2020-12-17 11:08

    You've got nothing to check in Main - you're using the new operator which never returns null (except for Nullable).

    It would be entirely reasonable to check in PrintAge, particularly if it were made public. (For private APIs it's less important to do argument checking, but it can still be very useful.)

    if (person == null)
    {
        throw new ArgumentNullException("person");
    }
    

    These days in C# 3.0 I usually use an extension method for this.

提交回复
热议问题