Is passing null in to a method acceptable

前端 未结 5 2082
夕颜
夕颜 2021-01-02 16:03

Null is an odd data type for me, it seems as though it is wrong to ever use, maybe its the null pointer errors i got so often as a beginner that now have me associating any

5条回答
  •  天命终不由人
    2021-01-02 16:27

    It is absolutely fine to pass null to methods. However, if you have a csae where you might not need to pass a variable, consider overloading.

    The reason why you might pass a null is because you might have a method with quite a few parameters and you do not wan to implement all possible overloads.

    I personally would not use optional parameters - there are many discussions on this very subject because of the issue with the method as Contract which is outside the scope of this question.


    UPDATE

    Correct way to do it is not to duplicate code but let overloads call each other:

    public void Foo(A a)
    {
        Foo(a, null);
    }
    public void Foo(A a, B b)
    {
            // .......
    }
    

    This will tell client of this code:

    • You can call method with A only
    • You can call method with A and B

    If I have only the second method, the client would not know if it is OK to pass null.

提交回复
热议问题