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. General Programming
  3. C#
  4. Tuples in Functions

Tuples in Functions

Scheduled Pinned Locked Moved C#
csharplinqtestingbeta-testinghelp
18 Posts 9 Posters 2 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.
  • C Offline
    C Offline
    computerpublic
    wrote on last edited by
    #1

    Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace Testing_Functions
    {
    class Program
    {
    public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
    {
    Double Test_Val = Val1 + Val2 + Val3;
    Double Test_2 = 7;
    return Tuple(Test_Val, Test_2);
    }
    static void Main(string[] args)
    {
    Double A = 1, B = 2, C = 3;
    Tuple Result = Test(A,B,C);
    Console.WriteLine("{0}", Result);
    }
    }
    }

    W R D L K 7 Replies Last reply
    0
    • C computerpublic

      Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;

      namespace Testing_Functions
      {
      class Program
      {
      public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
      {
      Double Test_Val = Val1 + Val2 + Val3;
      Double Test_2 = 7;
      return Tuple(Test_Val, Test_2);
      }
      static void Main(string[] args)
      {
      Double A = 1, B = 2, C = 3;
      Tuple Result = Test(A,B,C);
      Console.WriteLine("{0}", Result);
      }
      }
      }

      W Offline
      W Offline
      Wayne Gaylard
      wrote on last edited by
      #2

      A tuple is a reference object, so you need to create one using the new keyword. Try this :-

      public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
      {
      Double Test_Val = Val1 + Val2 + Val3;
      Double Test_2 = 7;
      return new Tuple<double, double>(Test_Val, Test_2);
      }

      static void Main(string[] args)
      {
      Double A = 1, B = 2, C = 3;
      Tuple<double,double> Result = Test(A, B, C);
      Console.WriteLine("{0} {1}", Result.Item1 , Result.Item2 );
      Console.ReadLine();
      }

      When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman

      L 1 Reply Last reply
      0
      • C computerpublic

        Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;

        namespace Testing_Functions
        {
        class Program
        {
        public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
        {
        Double Test_Val = Val1 + Val2 + Val3;
        Double Test_2 = 7;
        return Tuple(Test_Val, Test_2);
        }
        static void Main(string[] args)
        {
        Double A = 1, B = 2, C = 3;
        Tuple Result = Test(A,B,C);
        Console.WriteLine("{0}", Result);
        }
        }
        }

        R Offline
        R Offline
        Ravi Bhavnani
        wrote on last edited by
        #3

        To create a Tuple, use one of the generic constructors (or the static Tuple.Create() methods).  I believe this is what you want to do:

        var result = new Tuple(a, b, c);
        return new Tuple(test_val, test_2);

        [edit] To the univoter: Thank you for downvoting me because I was writing my reply at the same time as the first reponse (Wes) but didn't click the "Post Message" button in time. :doh: [/edit] /ravi

        My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

        1 Reply Last reply
        0
        • W Wayne Gaylard

          A tuple is a reference object, so you need to create one using the new keyword. Try this :-

          public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
          {
          Double Test_Val = Val1 + Val2 + Val3;
          Double Test_2 = 7;
          return new Tuple<double, double>(Test_Val, Test_2);
          }

          static void Main(string[] args)
          {
          Double A = 1, B = 2, C = 3;
          Tuple<double,double> Result = Test(A, B, C);
          Console.WriteLine("{0} {1}", Result.Item1 , Result.Item2 );
          Console.ReadLine();
          }

          When I was a coder, we worked on algorithms. Today, we memorize APIs for countless libraries — those libraries have the algorithms - Eric Allman

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

          Wayne Gaylard wrote:

          A tuple is a reference object, so you need to create one using the new keyword.

          I suppose that's true. IMO that looks a lot like it wouldn't have been necessary if Tuple had been a value type though, but it would have been.

          1 Reply Last reply
          0
          • C computerpublic

            Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;

            namespace Testing_Functions
            {
            class Program
            {
            public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
            {
            Double Test_Val = Val1 + Val2 + Val3;
            Double Test_2 = 7;
            return Tuple(Test_Val, Test_2);
            }
            static void Main(string[] args)
            {
            Double A = 1, B = 2, C = 3;
            Tuple Result = Test(A,B,C);
            Console.WriteLine("{0}", Result);
            }
            }
            }

            D Offline
            D Offline
            DaveyM69
            wrote on last edited by
            #5

            You have the answer to your question, this is just a comment regarding the casing of your parameters, variables etc. There are some generally accepted rules for casing which makes code at a glance easier to read and understand. See here[^]. It is not normally recommended to use underscores, they don't add any clarity, and abbreviations are discouraged. Taking the above into consideration your code would look like this:

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;

            namespace TestingFunctions
            {
            class Program
            {
            public static Tuple<double, double> Test(double value1, double value2, double value3)
            {
            double result1 = value1 + value2 + value3;
            double result2 = 7;
            return new Tuple(result1, result2);
            }
            static void Main(string[] args)
            {
            double a = 1, b = 2, c = 3;
            Tuple result = Test(a, b, c);
            Console.WriteLine("{0}", result);
            }
            }
            }

            This makes no difference to the execution of the code, it is just a personal (or company if you code professionaly) matter of style. There are also many differing opinions on some finer points!

            Dave
            Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
            BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

            B 1 Reply Last reply
            0
            • C computerpublic

              Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.

              using System;
              using System.Collections.Generic;
              using System.Linq;
              using System.Text;

              namespace Testing_Functions
              {
              class Program
              {
              public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
              {
              Double Test_Val = Val1 + Val2 + Val3;
              Double Test_2 = 7;
              return Tuple(Test_Val, Test_2);
              }
              static void Main(string[] args)
              {
              Double A = 1, B = 2, C = 3;
              Tuple Result = Test(A,B,C);
              Console.WriteLine("{0}", Result);
              }
              }
              }

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

              You can return more than 2 value from function. There are 2 way but I suggest you second one. 1. You can change your Method type to object[]. 2. Create a class and its member can be what you need to return. for example if you want to return 3 Double type value use these:

              public class Result
              {
              public double FirstNumber { get; set; }
              public double SecondNumber { get; set; }
              public double ThirdNumber { get; set; }
              // And you can create more ....
              }

              Then in your function:

              public static Result Do(params double[] numbers)
              {
              Result result = new Result();

              result.FirstNumber = numbers\[0\] - numbers\[1\];
              
              foreach (double number in numbers)
                  result.SecondNumber += number;
              
              return result;
              

              }

              Meysam

              D 1 Reply Last reply
              0
              • D DaveyM69

                You have the answer to your question, this is just a comment regarding the casing of your parameters, variables etc. There are some generally accepted rules for casing which makes code at a glance easier to read and understand. See here[^]. It is not normally recommended to use underscores, they don't add any clarity, and abbreviations are discouraged. Taking the above into consideration your code would look like this:

                using System;
                using System.Collections.Generic;
                using System.Linq;
                using System.Text;

                namespace TestingFunctions
                {
                class Program
                {
                public static Tuple<double, double> Test(double value1, double value2, double value3)
                {
                double result1 = value1 + value2 + value3;
                double result2 = 7;
                return new Tuple(result1, result2);
                }
                static void Main(string[] args)
                {
                double a = 1, b = 2, c = 3;
                Tuple result = Test(a, b, c);
                Console.WriteLine("{0}", result);
                }
                }
                }

                This makes no difference to the execution of the code, it is just a personal (or company if you code professionaly) matter of style. There are also many differing opinions on some finer points!

                Dave
                Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
                BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

                B Offline
                B Offline
                BillWoodruff
                wrote on last edited by
                #7

                DaveyM69, no personal attack intended, but I think it is generally unhelpful, and off-topic, to respond to a poster, struggling to get his, or her, head around a "best practice" technical strategy, with a "sermon" on variable-naming, and code-style: a topic on which there are many (widely debated) points of view. Consider the "religious wars" over just use of indentation, and/or, the virtues of the location of a block-open curly brace, and block-close curly brace: K&R, where the block-start curly brace follows the final close-parens of the argument list (usually preceded by a space) vs. the practice of adding a line break after the end of the argument list, then the open-curly-brace, followed by another line-break, and then use of indentation. Perhaps long ago, the very limited memory available in developer's machines made minimizing white-space desirable: but that is no longer the case. The fact is that if you get employed in a working team with a substantial code-base, you will have to adopt to their notation and casing conventions. And, some code transformations, such as KR style brace use <==> line-break-indent style, are easily done with very simple Regex expressions. And, conventions, like use of braces, may have very different behaviors from language to language: example: JavaScript: variables declared inside {} are not locally-scoped and disposed; they are global. For this reason, I voted your response a #1. best, Bill

                "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

                D 1 Reply Last reply
                0
                • B BillWoodruff

                  DaveyM69, no personal attack intended, but I think it is generally unhelpful, and off-topic, to respond to a poster, struggling to get his, or her, head around a "best practice" technical strategy, with a "sermon" on variable-naming, and code-style: a topic on which there are many (widely debated) points of view. Consider the "religious wars" over just use of indentation, and/or, the virtues of the location of a block-open curly brace, and block-close curly brace: K&R, where the block-start curly brace follows the final close-parens of the argument list (usually preceded by a space) vs. the practice of adding a line break after the end of the argument list, then the open-curly-brace, followed by another line-break, and then use of indentation. Perhaps long ago, the very limited memory available in developer's machines made minimizing white-space desirable: but that is no longer the case. The fact is that if you get employed in a working team with a substantial code-base, you will have to adopt to their notation and casing conventions. And, some code transformations, such as KR style brace use <==> line-break-indent style, are easily done with very simple Regex expressions. And, conventions, like use of braces, may have very different behaviors from language to language: example: JavaScript: variables declared inside {} are not locally-scoped and disposed; they are global. For this reason, I voted your response a #1. best, Bill

                  "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

                  D Offline
                  D Offline
                  DaveyM69
                  wrote on last edited by
                  #8

                  I believe some 'generally accepted' conventions should be followed as early as possible as code legibility and comprehension can be greatly increased for both the individual and anyone reviewing the code. I did point out there were differing opinions too and also mentioned that companies have their own styles. In my opinion it was far from a sermon; One sentence followed by a code example does not a sermon make.

                  BillWoodruff wrote:

                  For this reason, I voted your response a #1

                  That is your prerogative, but perhaps somewhat extreme? No matter, CP reputation points are the least of my concerns in life!

                  Dave
                  Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
                  BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

                  1 Reply Last reply
                  0
                  • L Lost User

                    You can return more than 2 value from function. There are 2 way but I suggest you second one. 1. You can change your Method type to object[]. 2. Create a class and its member can be what you need to return. for example if you want to return 3 Double type value use these:

                    public class Result
                    {
                    public double FirstNumber { get; set; }
                    public double SecondNumber { get; set; }
                    public double ThirdNumber { get; set; }
                    // And you can create more ....
                    }

                    Then in your function:

                    public static Result Do(params double[] numbers)
                    {
                    Result result = new Result();

                    result.FirstNumber = numbers\[0\] - numbers\[1\];
                    
                    foreach (double number in numbers)
                        result.SecondNumber += number;
                    
                    return result;
                    

                    }

                    Meysam

                    D Offline
                    D Offline
                    DaveyM69
                    wrote on last edited by
                    #9

                    Why is your result class better than using Tuple? Using params double[] may be a good idea for extensibility. If doing this however, it's important to check that numbers isn't null, and then check it's Length before using indexers otherwise some nasty exceptions may get thrown at some point.

                    Dave
                    Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
                    BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

                    L 1 Reply Last reply
                    0
                    • C computerpublic

                      Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.

                      using System;
                      using System.Collections.Generic;
                      using System.Linq;
                      using System.Text;

                      namespace Testing_Functions
                      {
                      class Program
                      {
                      public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
                      {
                      Double Test_Val = Val1 + Val2 + Val3;
                      Double Test_2 = 7;
                      return Tuple(Test_Val, Test_2);
                      }
                      static void Main(string[] args)
                      {
                      Double A = 1, B = 2, C = 3;
                      Tuple Result = Test(A,B,C);
                      Console.WriteLine("{0}", Result);
                      }
                      }
                      }

                      K Offline
                      K Offline
                      Keith Barrow
                      wrote on last edited by
                      #10

                      OK, I realise I suggested the Tuple thing in the thread below. What you have will work (when fixed) and is arguably correct. However if the return value "means" something as a pair it would be better in a language like C# creating a class or struct to contain them. One rule of thumb is if you can give your return "thing" a sensible name. Let's say for the sake of argument the return values represent a x/y co-ordinate pair. If this were the case then you'd be better of creating a class or struct. If the values are really two results from a calculation (as you have in your example) a tuple is good. The point of the class is that it gives semantic meaning to your program, which developers that follow you can understand. [Edit] This came to me after reading Bill's reply below. One thing that you also need to consider with the tuple is that it is reliant on the code consuming the class knowing what order the values were put in (and your code putting them in the right order), if you were returning say a string and a double there would be less problem. That said creating a container class or struct the values would be explicitly named, reducing the potential for error. Hopefully this isn't too confusing, getting to grips with programming is quite a task. This is a good read[^] if you are just starting out, it isn't as negative as the first few paragraphs suggest.

                      Sort of a cross between Lawrence of Arabia and Dilbert.[^]
                      -Or-
                      A Dead ringer for Kate Winslett[^]

                      1 Reply Last reply
                      0
                      • C computerpublic

                        Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.

                        using System;
                        using System.Collections.Generic;
                        using System.Linq;
                        using System.Text;

                        namespace Testing_Functions
                        {
                        class Program
                        {
                        public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
                        {
                        Double Test_Val = Val1 + Val2 + Val3;
                        Double Test_2 = 7;
                        return Tuple(Test_Val, Test_2);
                        }
                        static void Main(string[] args)
                        {
                        Double A = 1, B = 2, C = 3;
                        Tuple Result = Test(A,B,C);
                        Console.WriteLine("{0}", Result);
                        }
                        }
                        }

                        B Offline
                        B Offline
                        BillWoodruff
                        wrote on last edited by
                        #11

                        Between the responses to your first post, the responses to this post, and the (strangely out of place) discussion on the Lounge[^], you have a of ideas, and alternate strategies for using Tuples. I want to respond directly to your question about using Tuples. In my opinion, they can best be described as a "bag of pairs" where, for every pair in the bag: the first element, of the pair, is a Type; and, the second element is a value of that Type. And, do keep in mind that Tuples were introduced in .NET 4.0. So, they are most appropriate, imho, if you need to return a bunch of different types: if every Type in your Tuple elements is the same: then use one of the other strategies, or a generic List<Type>, or another method. Let me try and make this concrete for you: you can download this project (with source) compiled against .NET 4.0 here:[^]. 1. create a simple 'WinForms application: drop a 'CheckBox, a 'DateTimePicker, a 'TextBox, and a 'NumericUpDown[1] on the main Form. 2. put two 'Buttons on the Form: title the first 'Button "Save Tuple," and the second "Restore Tuple." Now let's look at what happens using a real Tuple in action: (attention: code-style obsessive-compulsives: I am using extra indentation, and line-breaks, here for clarity for the OP, it would not be my standard style): 1. first you declare a Form-scoped variable of Type Tuple for re-use:

                        private Tuple<CheckState, DateTime, string, decimal> _fourTuple;

                        1. You run the application, change the values of any of the four controls any way you like, and click the "Save Tuple" button: this code executes:

                        private void SaveTupleButtonClick(object sender, EventArgs e)
                        {
                        _fourTuple = Tuple.Create
                        (
                        checkBox1.CheckState,
                        dateTimePicker1.Value,
                        textBox1.Text,
                        numericUpDown1.Value
                        );
                        }

                        Here I am using the static Tuple.Create method, which was introduced in .NET FrameWork 4.0, to save some typing; it's exactly the same as if I wrote the fuller version:

                        private void SaveTupleButton_Click(object sender, EventArgs e)
                        {
                        _fourTuple = new Tuple
                        (
                        checkBox1.CheckState,
                        dateTimePicker1.Value,
                        textBox1.Text,
                        numericUpDown1.Va

                        K L 2 Replies Last reply
                        0
                        • D DaveyM69

                          Why is your result class better than using Tuple? Using params double[] may be a good idea for extensibility. If doing this however, it's important to check that numbers isn't null, and then check it's Length before using indexers otherwise some nasty exceptions may get thrown at some point.

                          Dave
                          Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
                          BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

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

                          Yeah, you are right; But my point was about "how to extend our return values count". If you disagree with params, just overload the method.

                          Meysam

                          1 Reply Last reply
                          0
                          • B BillWoodruff

                            Between the responses to your first post, the responses to this post, and the (strangely out of place) discussion on the Lounge[^], you have a of ideas, and alternate strategies for using Tuples. I want to respond directly to your question about using Tuples. In my opinion, they can best be described as a "bag of pairs" where, for every pair in the bag: the first element, of the pair, is a Type; and, the second element is a value of that Type. And, do keep in mind that Tuples were introduced in .NET 4.0. So, they are most appropriate, imho, if you need to return a bunch of different types: if every Type in your Tuple elements is the same: then use one of the other strategies, or a generic List<Type>, or another method. Let me try and make this concrete for you: you can download this project (with source) compiled against .NET 4.0 here:[^]. 1. create a simple 'WinForms application: drop a 'CheckBox, a 'DateTimePicker, a 'TextBox, and a 'NumericUpDown[1] on the main Form. 2. put two 'Buttons on the Form: title the first 'Button "Save Tuple," and the second "Restore Tuple." Now let's look at what happens using a real Tuple in action: (attention: code-style obsessive-compulsives: I am using extra indentation, and line-breaks, here for clarity for the OP, it would not be my standard style): 1. first you declare a Form-scoped variable of Type Tuple for re-use:

                            private Tuple<CheckState, DateTime, string, decimal> _fourTuple;

                            1. You run the application, change the values of any of the four controls any way you like, and click the "Save Tuple" button: this code executes:

                            private void SaveTupleButtonClick(object sender, EventArgs e)
                            {
                            _fourTuple = Tuple.Create
                            (
                            checkBox1.CheckState,
                            dateTimePicker1.Value,
                            textBox1.Text,
                            numericUpDown1.Value
                            );
                            }

                            Here I am using the static Tuple.Create method, which was introduced in .NET FrameWork 4.0, to save some typing; it's exactly the same as if I wrote the fuller version:

                            private void SaveTupleButton_Click(object sender, EventArgs e)
                            {
                            _fourTuple = new Tuple
                            (
                            checkBox1.CheckState,
                            dateTimePicker1.Value,
                            textBox1.Text,
                            numericUpDown1.Va

                            K Offline
                            K Offline
                            Keith Barrow
                            wrote on last edited by
                            #13

                            Vote of 5: Coherent, well though out and correct. I'd have been tempted to suggest we also have n-Tuple generics(ish), which if I had my way I'd have called then nuples.

                            Sort of a cross between Lawrence of Arabia and Dilbert.[^]
                            -Or-
                            A Dead ringer for Kate Winslett[^]

                            1 Reply Last reply
                            0
                            • C computerpublic

                              Basically I am experimenting with Tuple for the first time and I am completely out of my element. I have no idea of how to correct the errors I am getting. Can someone please help.

                              using System;
                              using System.Collections.Generic;
                              using System.Linq;
                              using System.Text;

                              namespace Testing_Functions
                              {
                              class Program
                              {
                              public static Tuple<double, double> Test(Double Val1, Double Val2, Double Val3)
                              {
                              Double Test_Val = Val1 + Val2 + Val3;
                              Double Test_2 = 7;
                              return Tuple(Test_Val, Test_2);
                              }
                              static void Main(string[] args)
                              {
                              Double A = 1, B = 2, C = 3;
                              Tuple Result = Test(A,B,C);
                              Console.WriteLine("{0}", Result);
                              }
                              }
                              }

                              B Offline
                              B Offline
                              BillWoodruff
                              wrote on last edited by
                              #14

                              Leppie wrote[^] re: the discussion of the use of Tuples (on the Lounge):

                              "Anonymous classes handle most of these cases and cleaner in my opinion. Who knows what Item0 and Item1 and Item2 is?"

                              .Of course Leppie is absolutely right: Tuple elements cannot be accessed by index; they cannot be foreach iterated, and, the following "legal" way to find out, at run-time, what Type an Item1 ... Item#n is, for example: "_fourTuple.Item1.GetType();" is something that would make me gag if I saw it in "real code." The main reason I am writing this is to ask Leppie to please reply with an example of the use of anonymous classes, which interests me very much, and I think will add value to this discussion. thanks, Bill

                              "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

                              B 1 Reply Last reply
                              0
                              • B BillWoodruff

                                Between the responses to your first post, the responses to this post, and the (strangely out of place) discussion on the Lounge[^], you have a of ideas, and alternate strategies for using Tuples. I want to respond directly to your question about using Tuples. In my opinion, they can best be described as a "bag of pairs" where, for every pair in the bag: the first element, of the pair, is a Type; and, the second element is a value of that Type. And, do keep in mind that Tuples were introduced in .NET 4.0. So, they are most appropriate, imho, if you need to return a bunch of different types: if every Type in your Tuple elements is the same: then use one of the other strategies, or a generic List<Type>, or another method. Let me try and make this concrete for you: you can download this project (with source) compiled against .NET 4.0 here:[^]. 1. create a simple 'WinForms application: drop a 'CheckBox, a 'DateTimePicker, a 'TextBox, and a 'NumericUpDown[1] on the main Form. 2. put two 'Buttons on the Form: title the first 'Button "Save Tuple," and the second "Restore Tuple." Now let's look at what happens using a real Tuple in action: (attention: code-style obsessive-compulsives: I am using extra indentation, and line-breaks, here for clarity for the OP, it would not be my standard style): 1. first you declare a Form-scoped variable of Type Tuple for re-use:

                                private Tuple<CheckState, DateTime, string, decimal> _fourTuple;

                                1. You run the application, change the values of any of the four controls any way you like, and click the "Save Tuple" button: this code executes:

                                private void SaveTupleButtonClick(object sender, EventArgs e)
                                {
                                _fourTuple = Tuple.Create
                                (
                                checkBox1.CheckState,
                                dateTimePicker1.Value,
                                textBox1.Text,
                                numericUpDown1.Value
                                );
                                }

                                Here I am using the static Tuple.Create method, which was introduced in .NET FrameWork 4.0, to save some typing; it's exactly the same as if I wrote the fuller version:

                                private void SaveTupleButton_Click(object sender, EventArgs e)
                                {
                                _fourTuple = new Tuple
                                (
                                checkBox1.CheckState,
                                dateTimePicker1.Value,
                                textBox1.Text,
                                numericUpDown1.Va

                                L Offline
                                L Offline
                                leppie
                                wrote on last edited by
                                #15

                                While anonymous classes will not here, in this situation based on the amount of usage and 'decoration' required, a concrete class IMO would be a better option. Remember you only have to write it once.

                                struct State
                                {
                                public CheckState Value;
                                public DateTime When;
                                public string By;
                                public decimal Amount;
                                }

                                A struct already implements hashcode and equality too. Now imagine you need an extra field. In the case of a class/struct, no problem, but your Tuple will require changes across the board, even if you just add it to the end.

                                IronScheme
                                ((λ (x) `(,x ',x)) '(λ (x) `(,x ',x)))

                                B 1 Reply Last reply
                                0
                                • L leppie

                                  While anonymous classes will not here, in this situation based on the amount of usage and 'decoration' required, a concrete class IMO would be a better option. Remember you only have to write it once.

                                  struct State
                                  {
                                  public CheckState Value;
                                  public DateTime When;
                                  public string By;
                                  public decimal Amount;
                                  }

                                  A struct already implements hashcode and equality too. Now imagine you need an extra field. In the case of a class/struct, no problem, but your Tuple will require changes across the board, even if you just add it to the end.

                                  IronScheme
                                  ((λ (x) `(,x ',x)) '(λ (x) `(,x ',x)))

                                  B Offline
                                  B Offline
                                  BillWoodruff
                                  wrote on last edited by
                                  #16

                                  Thanks, Leppie, for "weighing in here:" your comment on anonymous classes has lead me to some interesting technical geography. Of course, I am still eager to here how you use anonymous classes :) I've been reading, on various web-sources, mainly StackOverFlow, discussions of anonymous classes: the problem with SO is that while the OP may mention the words "anonymous classes," the discussion soon turns, it seems, to anonymous types, and use of 'dynamic, and 'var. This SO thread was interesting for the sheer volume of responses and debates:"A generic list of anonymous class"[^]. Probably the two most interesting (and exotic) discussions I found were by Jon Skeet: "Horrible grotty hack: returning an anonymous type instance"[^], and on a site called DevCurry: "Look Ma! No Classes – Creating Generic List(T) collection of Anonymous Types and calling Extension Methods"[^]. In the comments section of the Skeet article is this wonderful exchange between Jon and one "Erik:" # re: Horrible grotty hack: returning an anonymous type instance "This is one of those examples where relying on internal implementations can bite you, I imagine - since anonymous types are by design not supposed to leave private scope, the compiler team is free to do whatever they want with the actual implementation. Thanks for the brain-twitch, though, Jon. =) Friday, January 09, 2009 12:21 PM by Erik" # re: Horrible grotty hack: returning an anonymous type instance "@Erik: No, it's not implementation-dependent. The compiler-generated name is, but the language spec guarantees that two anonymous object creation expressions using the same property names and compile-time types within the same assembly will create instances of the same type. See section 7.5.10.6 of the C# 3.0 spec. Friday, January 09, 2009 1:48 PM by skeet" best, Bill

                                  "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 1 Reply Last reply
                                  0
                                  • B BillWoodruff

                                    Thanks, Leppie, for "weighing in here:" your comment on anonymous classes has lead me to some interesting technical geography. Of course, I am still eager to here how you use anonymous classes :) I've been reading, on various web-sources, mainly StackOverFlow, discussions of anonymous classes: the problem with SO is that while the OP may mention the words "anonymous classes," the discussion soon turns, it seems, to anonymous types, and use of 'dynamic, and 'var. This SO thread was interesting for the sheer volume of responses and debates:"A generic list of anonymous class"[^]. Probably the two most interesting (and exotic) discussions I found were by Jon Skeet: "Horrible grotty hack: returning an anonymous type instance"[^], and on a site called DevCurry: "Look Ma! No Classes – Creating Generic List(T) collection of Anonymous Types and calling Extension Methods"[^]. In the comments section of the Skeet article is this wonderful exchange between Jon and one "Erik:" # re: Horrible grotty hack: returning an anonymous type instance "This is one of those examples where relying on internal implementations can bite you, I imagine - since anonymous types are by design not supposed to leave private scope, the compiler team is free to do whatever they want with the actual implementation. Thanks for the brain-twitch, though, Jon. =) Friday, January 09, 2009 12:21 PM by Erik" # re: Horrible grotty hack: returning an anonymous type instance "@Erik: No, it's not implementation-dependent. The compiler-generated name is, but the language spec guarantees that two anonymous object creation expressions using the same property names and compile-time types within the same assembly will create instances of the same type. See section 7.5.10.6 of the C# 3.0 spec. Friday, January 09, 2009 1:48 PM by skeet" best, Bill

                                    "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
                                    leppie
                                    wrote on last edited by
                                    #17

                                    Quote:

                                    I am still eager to here how you use anonymous classes

                                    In the aforementioned case, it would be impossible :) The rest of the possible cases is indeed described by Jon Skeet, and while he calls them a 'hack', any of those ways should be preferred over tuples (IMO).

                                    IronScheme
                                    ((λ (x) `(,x ',x)) '(λ (x) `(,x ',x)))

                                    1 Reply Last reply
                                    0
                                    • B BillWoodruff

                                      Leppie wrote[^] re: the discussion of the use of Tuples (on the Lounge):

                                      "Anonymous classes handle most of these cases and cleaner in my opinion. Who knows what Item0 and Item1 and Item2 is?"

                                      .Of course Leppie is absolutely right: Tuple elements cannot be accessed by index; they cannot be foreach iterated, and, the following "legal" way to find out, at run-time, what Type an Item1 ... Item#n is, for example: "_fourTuple.Item1.GetType();" is something that would make me gag if I saw it in "real code." The main reason I am writing this is to ask Leppie to please reply with an example of the use of anonymous classes, which interests me very much, and I think will add value to this discussion. thanks, Bill

                                      "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

                                      B Offline
                                      B Offline
                                      BobJanova
                                      wrote on last edited by
                                      #18

                                      I agree in general but you know, statically, what the type of the second item of a Tuple is. If the Tuple is Tuple<T, U> then the type of the second item is U.

                                      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