Mark parameters as NOT nullable in C#/.NET?

后端 未结 6 2006
粉色の甜心
粉色の甜心 2020-12-02 21:53

Is there a simple attribute or data contract that I can assign to a function parameter that prevents null from being passed in C#/.NET? Ideally this would also

6条回答
  •  离开以前
    2020-12-02 22:12

    Ok this reply is a bit late, but here is how I am solving it:

    public static string Default(this string x)
    {
        return x ?? "";
    }
    

    Use this exension method then you can treat null and empty string as the same thing.

    E.g.

    if (model.Day.Default() == "")
    {
        //.. Do something to handle no Day ..
    }
    

    Not ideal I know as you have to remember to call default everywhere but it is one solution.

提交回复
热议问题