What's the purpose of the Tuple(T1)/Singleton in .net?

后端 未结 4 1768
难免孤独
难免孤独 2020-12-03 13:06

One of the Tuple Types in .net 4 is a Single-Element Tuple. I just wonder what the purpose of this struct is?

The only use I saw is when using in the 8+ Tuple as it

4条回答
  •  误落风尘
    2020-12-03 14:07

    Although this is an old thread, I was preparing an answer for Why use a 1-tuple, Tuple in C#? , which is now marked as a duplicate.

    One possible usage of a 1-Tuple, is to return a null instance if there is no value, but that null of the item value itself, does not mean there is no result.

    For example (not a very good real life example, but hopefully it conveys the point)

        static List List = new List {"a", "b", null, "c"};
    
        static Tuple GetItemAtIndex(int index)
        {
            if (index < 0 || index >= List.Count)
                return null;
            return Tuple.Create(List[index]);
        }
    

    The calling code would know that when the tuple itself is null, it did not exist in the list, but if Item1 is null, there actually was a null item in the list. Of course in this example, plenty of better workarounds exist, but it could also apply to a result out of a database: no result found or a result that is null.

    Extending that same logic, a Tuple can be used to easily create generic methods that can return null for any type. For example

        static Tuple GetSomething(RecType rec, Func fn)
        {
            if (rec == null) return null;
            //extra example, access would be checked by something like CheckCurrentUserAccess(rec)
            bool AccesDenied = true;
            if (AccesDenied) return null; //sometimes you don't want to throw an exception ;)
    
            return Tuple.Create(fn(rec));
        }
    

    You could return Nullable, but that would only work for structs, where this works with any type, albeit int, string, int?, MyClass, etc

提交回复
热议问题