Method with same name and signature but different return type in C#

后端 未结 9 1776
南旧
南旧 2020-12-08 01:01

I had an interview where I was asked the following:

Question: A method with same name and signature but different return type. Is it possible and what is this type c

9条回答
  •  遥遥无期
    2020-12-08 01:29

    I recently had this exact issue since I was parsing a config file with various types that all use a standard sort of config.Parse(string settingName) type interface.

    1st Solution Generic Method:

    T Parse (string settingName)
    {
        T Result;
        doParsing...
        return T;
    }
    

    I didn't really like this since it involved explicitly specifying the type that's being used such as someSetting = Parse("param");

    So the solution I used is redundant but much more clean in my opinion:

    T Parse (string settingName, out T result)
    {
        doParsing...
        return T;
    }
    

    The out variable and the return are identical so it's a bit redundant but it enables what I think is a much cleaner interface:

    setting = Parse("intparam", out setting);
    

    And you get methods that vary only by return type for a slight cost of redundancy. On top of that if the type of your data changes, for instance from a double to a float, then you everything will continue working just fine, whereas with the first solution you'd end up getting cannot implicitly convert errors.

提交回复
热议问题