Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. A Blatant Programming Question

A Blatant Programming Question

Scheduled Pinned Locked Moved The Lounge
questioncsharpdata-structureshelptutorial
60 Posts 28 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • R Roger Wright

    Not really... ;P There's a discussion going on in the C# forum about Tuples, and I'm curious what one would use them for. From browsing VS2010 Help, it appears to me that this is a way to make vectors of mixed types which, if used as a type for an Array, could allow mixed arrays. Is this correct? And what would be an example of using such a beast? Wouldn't a dataset be more efficient? Enquiring minds want to know, as they say at the checkout counter. :)

    Will Rogers never met me.

    J Offline
    J Offline
    Jonathan C Dickinson
    wrote on last edited by
    #39

    The concept of using arrays has been bought up - and why use them instead of arrays. It's because arrays have no type safety - leading to logical bugs at runtime. For example: Buggy code:

    // I promise to return an array of length 2, with a String and Double.
    public static object[] DoStuff()
    {
    return new object[] { "Hello", 123 }; // Did you mean 123.0?
    }

    public static void Main()
    {
    var ret = DoStuff();
    var a = (string)ret[0]; // What happens if DoStuff() doesn't return the correct number of items?
    var b = (double)ret[1]; // As above, as well as what if the type is wrong (which it is)?
    }

    Contrast this with:

    // No comment required because this documents itself.
    public static Tuple DoStuff()
    {
    return Tuple.Create("Hello", 123); // Compiler error, not runtime error! Wooo!
    }

    public static void Main()
    {
    var ret = DoStuff();
    var a = ret.Item1; // Always succeeds.
    var b = ret.Item2; // Always succeeds.
    }

    Finally consider the [internal, clearly] extension method magic you can do. So basically they are needed when you need an array of fixed length where each element in the array is a strong type. Remember that C# is [typically] a strongly-typed language and Tuple is a great citizen in the .Net type system for any language that is strongly-typed (and functional languages like F# too). You could write a class that represents your return type/whatever, but then again, why do you use Dictionary<TKey, TValue>? Shouldn't you write a specific type for that? Tuple is as much as a strongly-typed primitive as an array (it was just previously missing); it just needs to be used correctly (see above paragraph). Edit: Yes, I know that it originates from functional languages, but as always the .Net Framework team are showing us that at the end of the day all things are the same: and today the functional features in C# feel like natural parts of a imperative language (even though previously they were not). I strongly feel that the same principle applies to Tuple. Yes, I know that a runtime based on multiple return values (like Go) would be more 'correct'; but the Tuple is the biggest bang for 'risk buck' - in addition you can use it in places other than return types. Basically, learn to love that your cheese was moved into the fridge (where it belongs).

    He who asks a question i

    1 Reply Last reply
    0
    • R Roger Wright

      Not really... ;P There's a discussion going on in the C# forum about Tuples, and I'm curious what one would use them for. From browsing VS2010 Help, it appears to me that this is a way to make vectors of mixed types which, if used as a type for an Array, could allow mixed arrays. Is this correct? And what would be an example of using such a beast? Wouldn't a dataset be more efficient? Enquiring minds want to know, as they say at the checkout counter. :)

      Will Rogers never met me.

      Y Offline
      Y Offline
      YvesDaoust
      wrote on last edited by
      #40

      When defined at compile-time, a tuple is nothing else than a struct (a class if you prefer) and each member is referenced by a name. The .NET Tuples allow defining them at run-time, referencing the members by an index, to allow some form of run-time polymorphism. You will use a .NET Tuple when the composition of the items is unknown until run-time, for instance if it is input by the user.

      1 Reply Last reply
      0
      • P Phil Martin

        Things I find them very useful for: - Returning multiple values without the bother of out or ref parameters, and so I don't have to make a whole other class. - Working with Enumerable.Zip - Keys into Dictionarys so I don't have to bother writing a fast and correct Equals and GetHashCode() methods - Ensuring immutability. Unlike an array, the items are readonly. An array is faster and nicer, but it's mutable, which is sometimes a pain.

        A Offline
        A Offline
        Adriaan Davel
        wrote on last edited by
        #41

        Agree with all, I sometimes use it to avoid writing a class and use it in my model only, if I want to construct a list of 'paired' types for a display for example

        ____________________________________________________________ Be brave little warrior, be VERY brave

        1 Reply Last reply
        0
        • R Roger Wright

          Not really... ;P There's a discussion going on in the C# forum about Tuples, and I'm curious what one would use them for. From browsing VS2010 Help, it appears to me that this is a way to make vectors of mixed types which, if used as a type for an Array, could allow mixed arrays. Is this correct? And what would be an example of using such a beast? Wouldn't a dataset be more efficient? Enquiring minds want to know, as they say at the checkout counter. :)

          Will Rogers never met me.

          R Offline
          R Offline
          Rob Grainger
          wrote on last edited by
          #42

          Not sure if you actually got an answer here, but the 20 or so results I scanned seemed hopelessly misguided. Tuples are used enormously in functional programming and are extremely useful in LINQ. With LINQ queries, you may have an object of type person with Name, Age, Gender, etc. Now if you execute "from Persons where age > 20 select Age, Gender", what is the type of the result: answer a tuple type with the first item an integer and the 2nd an enum type. This is where they are useful. They avoid having to litter your code with classes that add no meaningful information and are pure data values. They are commonly useful as return types, e.g. a tuple where the first item indicates if the 2nd is applicable. Many more usages exist.

          R 1 Reply Last reply
          0
          • R Roger Wright

            Not really... ;P There's a discussion going on in the C# forum about Tuples, and I'm curious what one would use them for. From browsing VS2010 Help, it appears to me that this is a way to make vectors of mixed types which, if used as a type for an Array, could allow mixed arrays. Is this correct? And what would be an example of using such a beast? Wouldn't a dataset be more efficient? Enquiring minds want to know, as they say at the checkout counter. :)

            Will Rogers never met me.

            U Offline
            U Offline
            User 2788383
            wrote on last edited by
            #43

            One of the best things tuples do is they allow you to return multiple values from a function instead of just one value as was the case in C# before C# 4.0.

            R 1 Reply Last reply
            0
            • B BillWoodruff

              I never thought I'd see the day when I'd vote anything posted by one of my very favorite posters, Roger Wright, a "one," but in this case I feel there is a compelling reason to do so based on what I view as a concern for the quality of CP as-a-whole, and I have fully explained that here on "Bugs and suggs:" [^]. best, Bill p.s. go ahead and down-vote me all you like: if my entire reputation on CP is wiped out, and I go "underwater," well: let's just say, I have "gills," and "don't give a damn" at nearly 69 years of age: in my opinion if a person by the time of their sixties doesn't know what their values are, and is not willing to go out-on-a-limb, and stand up for them, well ... you fill in the rest of the sentence, please ...

              "One of the few good things about modern times: If you die horribly on television, you will not have died in vain. You will have entertained us." Kurt Vonnegut

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #44

              You seem a bit uptight to me. But you explained yourself so it's a wash, IMHO.

              1 Reply Last reply
              0
              • G Garth J Lancaster

                Kenneth Haugland wrote:

                People that are too lazy to write classes?

                oh the arrogance of the young ... I'd suggest Tuples were around before c++, c#, and 'class' related constructs 'g'

                G Offline
                G Offline
                Gary Huck
                wrote on last edited by
                #45

                Garth J Lancaster wrote:

                I'd suggest Tuples were around before c++, c#, and 'class' related constructs

                ... as was Fortran, punch cards, ...

                1 Reply Last reply
                0
                • K Kenneth Haugland

                  We are talking about this[^]?

                  D Offline
                  D Offline
                  Dominic Amann
                  wrote on last edited by
                  #46

                  A map is essentially a collection of tuples, and I find maps incredibly useful. Often times I have a tuple in my code consisting of:

                  pair >

                  especially in database mapping.

                  K 1 Reply Last reply
                  0
                  • D Dominic Amann

                    A map is essentially a collection of tuples, and I find maps incredibly useful. Often times I have a tuple in my code consisting of:

                    pair >

                    especially in database mapping.

                    K Offline
                    K Offline
                    Kenneth Haugland
                    wrote on last edited by
                    #47

                    Never even crossed my mind :thumbsup:

                    1 Reply Last reply
                    0
                    • R Roger Wright

                      Not really... ;P There's a discussion going on in the C# forum about Tuples, and I'm curious what one would use them for. From browsing VS2010 Help, it appears to me that this is a way to make vectors of mixed types which, if used as a type for an Array, could allow mixed arrays. Is this correct? And what would be an example of using such a beast? Wouldn't a dataset be more efficient? Enquiring minds want to know, as they say at the checkout counter. :)

                      Will Rogers never met me.

                      F Offline
                      F Offline
                      Fred Flams
                      wrote on last edited by
                      #48

                      Tuples exist in various functionnal languages, F# has been mentionned but older languages such as lisp / caml / ocaml and other similar flavours had them already. It can be useful if you want to have lists of associated items without having to handle a dictionnary. i.e.: Dictionnary<string, BlueToothDevice> could be replaced by List<Tuple<string, BlueToothDevice>>, you keep the flexibility of a List object (AddRange, RemoveRange, ForAll and so on) and the capability of a dictionnary and the system of keys... Another use I quite like is when you design an API method that would like to return multiple values at once, as it is not possible, you can use Tuples instead: public bool DoSomethingUseful(int someValue1, string someValue2, ref double someExport1, ref shot someExport2) could be written: public Tuple<bool, double, short> DoSomethingUseful(int someValue1, string someValue2) thus eliminating the need to pass parameters by reference because the return value of a method is already used... I hope this post can help you make your mind about Tuples and their possible usage.

                      1 Reply Last reply
                      0
                      • R Roger Wright

                        Not really... ;P There's a discussion going on in the C# forum about Tuples, and I'm curious what one would use them for. From browsing VS2010 Help, it appears to me that this is a way to make vectors of mixed types which, if used as a type for an Array, could allow mixed arrays. Is this correct? And what would be an example of using such a beast? Wouldn't a dataset be more efficient? Enquiring minds want to know, as they say at the checkout counter. :)

                        Will Rogers never met me.

                        M Offline
                        M Offline
                        mjohns07
                        wrote on last edited by
                        #49

                        I believe programming with tuples fits best with the functional programming paradigm or a mixed functional/OOP style. If your functions return values instead of changing the state of objects, then you might want to use tuples. On a side note, Erik Meijer, from Microsoft, will be talking at GOTO Night Chicago[^] on August 23rd. I'll be there. He'll be talking about embracing purely functional programming in order to tackle concurrency and complexity. I bet if we watch some of Erik Meijer's videos on Channel 9, we will better understand tuples: C9 Lectures: Dr. Erik Meijer - Functional Programming Fundamentals, Chapter 1 of 13[^]

                        1 Reply Last reply
                        0
                        • G Gary R Wheeler

                          The big thing is that they save you from creating a throwaway class just to manage a small set of items. Apparently this is something the functional languages like F# do often. I'll freely admit though after I read the article I had a strong whiff of #define.

                          Software Zen: delete this;

                          M Offline
                          M Offline
                          mgkr
                          wrote on last edited by
                          #50

                          "save you from creating a throwaway class" ^^This Ask yourself how many times you've (mis-)used the out param, to have method "return" two values. Sometimes you need two values back, and creating a class/struct for just that one method to be able to return the two values is.. annoying (and clutters the code) Using a Tuple instead is the "clean" way of doing this (and it can be expanded to more than just two objects)

                          D 1 Reply Last reply
                          0
                          • M mgkr

                            "save you from creating a throwaway class" ^^This Ask yourself how many times you've (mis-)used the out param, to have method "return" two values. Sometimes you need two values back, and creating a class/struct for just that one method to be able to return the two values is.. annoying (and clutters the code) Using a Tuple instead is the "clean" way of doing this (and it can be expanded to more than just two objects)

                            D Offline
                            D Offline
                            DavidSherwood
                            wrote on last edited by
                            #51

                            The 'clean' way is not so clean because C# (and VB) do not have any language constructs to handle them. A function that would return a tuple will require some 'dirty' code to untangle the tuple. I thing tuples were added to .Net to support F#, which does make language constructs to deal with them. Until C# adds similar constructs, I don't see using them.

                            M 1 Reply Last reply
                            0
                            • R Rob Grainger

                              Not sure if you actually got an answer here, but the 20 or so results I scanned seemed hopelessly misguided. Tuples are used enormously in functional programming and are extremely useful in LINQ. With LINQ queries, you may have an object of type person with Name, Age, Gender, etc. Now if you execute "from Persons where age > 20 select Age, Gender", what is the type of the result: answer a tuple type with the first item an integer and the 2nd an enum type. This is where they are useful. They avoid having to litter your code with classes that add no meaningful information and are pure data values. They are commonly useful as return types, e.g. a tuple where the first item indicates if the 2nd is applicable. Many more usages exist.

                              R Offline
                              R Offline
                              Roger Wright
                              wrote on last edited by
                              #52

                              Cool! That makes sense to me! :-D

                              Will Rogers never met me.

                              R 1 Reply Last reply
                              0
                              • U User 2788383

                                One of the best things tuples do is they allow you to return multiple values from a function instead of just one value as was the case in C# before C# 4.0.

                                R Offline
                                R Offline
                                Roger Wright
                                wrote on last edited by
                                #53

                                I haven't needed to do that often, but I can see the value of this for a number of applications. Thanks! :-D

                                Will Rogers never met me.

                                1 Reply Last reply
                                0
                                • K Kenneth Haugland

                                  :laugh: Only the items could be anything, seems very much to resemble a list of different objects, witch you could send around without createing a class. I cant think of a use. WPF and binding seem to make them unnessecary, but what do I know... Im sure that someone will tell you that the planets existens depended on this class...

                                  M Offline
                                  M Offline
                                  Member 4608898
                                  wrote on last edited by
                                  #54

                                  Probably a direct mapping to the javascript array which can take just about anything.

                                  1 Reply Last reply
                                  0
                                  • R Roger Wright

                                    Cool! That makes sense to me! :-D

                                    Will Rogers never met me.

                                    R Offline
                                    R Offline
                                    Rob Grainger
                                    wrote on last edited by
                                    #55

                                    Glad it was helpful.

                                    1 Reply Last reply
                                    0
                                    • R Roger Wright

                                      Not really... ;P There's a discussion going on in the C# forum about Tuples, and I'm curious what one would use them for. From browsing VS2010 Help, it appears to me that this is a way to make vectors of mixed types which, if used as a type for an Array, could allow mixed arrays. Is this correct? And what would be an example of using such a beast? Wouldn't a dataset be more efficient? Enquiring minds want to know, as they say at the checkout counter. :)

                                      Will Rogers never met me.

                                      S Offline
                                      S Offline
                                      S Douglas
                                      wrote on last edited by
                                      #56

                                      Hi Roger, Just happened upon this thread (been a few days since I was last at CP on this computer). Turples are used heavily in MDX (Multi dimensional Expressions, for Multi Dimensional databases such as SSAS) where they create a subset of data on the fly. The data is not entirely known (the multi dimensional database does know the meta data of the database) until the user selects the data. I would guess that the class was added to aid in building MDX query interfaces.


                                      Common sense is admitting there is cause and effect and that you can exert some control over what you understand.

                                      1 Reply Last reply
                                      0
                                      • D DavidSherwood

                                        The 'clean' way is not so clean because C# (and VB) do not have any language constructs to handle them. A function that would return a tuple will require some 'dirty' code to untangle the tuple. I thing tuples were added to .Net to support F#, which does make language constructs to deal with them. Until C# adds similar constructs, I don't see using them.

                                        M Offline
                                        M Offline
                                        mgkr
                                        wrote on last edited by
                                        #57

                                        The "clean" was in ""'s - As it was compared to the misuse of the out param. Strictly speaking I agree it's not clean, and one ought to create a new class/struct. But... I also don't like to clutter my code with tiny helper classes with no other functionality than storing a few values, so I can return it from a method call. Pest or cholera... But either way, I still think it's "cleaner" (can we agree on that :cool:) than misusing the out parameter for this purpose (something I've also done... :-O )

                                        1 Reply Last reply
                                        0
                                        • R Roger Wright

                                          Not really... ;P There's a discussion going on in the C# forum about Tuples, and I'm curious what one would use them for. From browsing VS2010 Help, it appears to me that this is a way to make vectors of mixed types which, if used as a type for an Array, could allow mixed arrays. Is this correct? And what would be an example of using such a beast? Wouldn't a dataset be more efficient? Enquiring minds want to know, as they say at the checkout counter. :)

                                          Will Rogers never met me.

                                          S Offline
                                          S Offline
                                          Stefan_Lang
                                          wrote on last edited by
                                          #58

                                          There are a lot of uses for tuples in math, e. g. in group theory. They have been used in these areas for much longer than computers exist. Most of the time, the elements of a tuple in math are of a radically different kind. E. g. when you define an algebraic group, you build a tuple out of the basic set of numbers that your elements are based on (e. g. real numbers, complex numbers, integers, or something more exotic such as functions), and the rules for performing operations on your elements, such as addition, multiplication, whether these operations are associative or commutative, etc.. While I can imagine some mathematician rejoices at the ability to model such constructs in software directly, IMHO a simple class would serve the same purpose. Only better.

                                          R 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups