zoukankan      html  css  js  c++  java
  • Make a Dictionary method argument default to an empty dictionary instead of null

    Make a Dictionary method argument default to an empty dictionary instead of null

    Is there some way to make the default Dictionary empty?

    Yes, use the constructor instead of default:

    void Foo(Dictionary<string, string> parameter){
        if(parameter == null) parameter = new Dictionary<string,string>();
    }
    

    You could also make the parameter optional:

    void Foo(Dictionary<string, string> parameter = null)
    {
        if(parameter == null) parameter = new Dictionary<string,string>();
    }
    

    An optional parameter must be a compile time constant, that's why you can't use new Dictionary<string,string>() directly.


    According to the question if you can change the behaviour of the default keyword, no, you cannot return a different value. For reference types null is the default value and will be returned.

    C# language specs. §12.2:

    The default value of a variable depends on the type of the variable and is determined as follows:

    • For a variable of a value-type, the default value is the same as the value computed by the value-type’s default constructor (§11.1.2).
    • For a variable of a reference-type, the default value is null.

    Update: for what it's woth, you could use this extension (i wouldn't use it):

    public static T EmptyIfNull<T>(this T coll) 
        where T :  ICollection, new() // <-- Constrain to types with a default constructor and collections
    {
        if(coll == null)
            return new T();
        return coll;
    }
    

    Now you could use it in this way:

    Dictionary<string, string> parameter = null;
    Foo(parameter.EmptyIfNull());  // now an empty dictionary is passed
    

    But the last thing another programmer wants to see is thousands of lines of code peppered with .EmptyIfNull() everywhere just because the first guy was too lazy to use a constructor.

  • 相关阅读:
    CSU-ACM2020寒假集训比赛2
    js动画(一)
    响应式基本知识
    移动web基本知识
    premere cs4绿色版 安装 并且 视频导出 讲解
    样式重置
    html5图片标签与属性
    我眼中的科研
    Chrome浏览器上无法使用西瓜影音???
    双系统引导菜单设置
  • 原文地址:https://www.cnblogs.com/chucklu/p/14388013.html
Copyright © 2011-2022 走看看