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.
  • 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