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. Returning multiple values from methods

Returning multiple values from methods

Scheduled Pinned Locked Moved C#
csharpdesigncollaborationhelp
12 Posts 6 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.
  • B bjoernen

    One thing that have annoyed me with most languages I've used (including C#) is the problem with returning multiple values from methods. The following works, but is not very neat, and to my opinion is not very readable: a = BiteMe(x, y, z, out b, out c); Look how elegant Lua solves this: a, b, c = BiteMe(x, y, z); And notice how easy you can swap variable values in Lua: a, b = b, a; Maybe something for the C# language design team. Regards, Björn Morén Stockholm, Sweden

    M Offline
    M Offline
    Marc Clifton
    wrote on last edited by
    #3

    bjoernen wrote: One thing that have annoyed me with most languages I've used (including C#) is the problem with returning multiple values from methods. Yes, this frustrating for me too. However, I've found that the best way to manage this is to pass a struct (by reference!) or a class (which is automatically by ref). It's better code, more understandable, easier to extend, and gives you a lot of other benefits too. In fact, I need to go clean up a bunch of code right now that could really use a class instead of discrete parameters! Marc Microsoft MVP, Visual C# MyXaml MyXaml Blog

    B 1 Reply Last reply
    0
    • B bjoernen

      One thing that have annoyed me with most languages I've used (including C#) is the problem with returning multiple values from methods. The following works, but is not very neat, and to my opinion is not very readable: a = BiteMe(x, y, z, out b, out c); Look how elegant Lua solves this: a, b, c = BiteMe(x, y, z); And notice how easy you can swap variable values in Lua: a, b = b, a; Maybe something for the C# language design team. Regards, Björn Morén Stockholm, Sweden

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

      You could just create a struct class(es) Tuple2(...9) and just return that. eg Tuple3 t = BiteMe(x,y,z); Alternatively I use: void BiteMe(out x, out y, out z) top secret xacc-ide 0.0.1

      1 Reply Last reply
      0
      • C Colin Angus Mackay

        I've used a language that is like Lua in this respect (it is called Magik and was created by a company called Smallworld in the late 80s). What I found most annoying was that a method was returing multiple values and I had no idea what order they were in or what they were because the method was named GetX(), but it also returned Y and Z - The compiler would never complain if I missed one, or didn't get the order right, because receiving the return parameters from a method is optional. I kept having to refer to the documentation as it was not intuative as to what was being returned. At least with C# (and C++/C et al) all these additional parameters are named so it is easy to tell what they represent, and that you have to provide something for them to be received into so you don't accidentatlly miss one.


        "You can have everything in life you want if you will just help enough other people get what they want." --Zig Ziglar The Second EuroCPian Event will be in Brussels on the 4th of September Can't manage to P/Invoke that Win32 API in .NET? Why not do interop the wiki way!

        B Offline
        B Offline
        bjoernen
        wrote on last edited by
        #5

        I dont think this would be a problem if the syntax for declaring return values would be very similar to declaring input parameters: public int, string, string BiteMe(float x, float y, float z) { } or maybe the following is more readable, and maps to xml comments better: public int a, string b, string c BiteMe(float x, float y, float z) { return Convert.ToInt32(x), y.ToString(), z.ToString(); } Regards, Björn Morén Stockholm, Sweden

        1 Reply Last reply
        0
        • M Marc Clifton

          bjoernen wrote: One thing that have annoyed me with most languages I've used (including C#) is the problem with returning multiple values from methods. Yes, this frustrating for me too. However, I've found that the best way to manage this is to pass a struct (by reference!) or a class (which is automatically by ref). It's better code, more understandable, easier to extend, and gives you a lot of other benefits too. In fact, I need to go clean up a bunch of code right now that could really use a class instead of discrete parameters! Marc Microsoft MVP, Visual C# MyXaml MyXaml Blog

          B Offline
          B Offline
          bjoernen
          wrote on last edited by
          #6

          Yes, I use those too, but under protest. ;-) But I still find it counter-productive to be forced to create output structs. Nobody uses input structs, because the C# language handles a collection of input parameters elegantly. In my mind output result values ought to be handled the same way. Lets say you have 10 different methods that each return a result object, but from different classes, for instance Point, Rectangle, ArrayList, etc (some of the framework structs and classes). Lets say you also want to be able to tell if the operation went ok, for all those methods, so you'll need a second output parameter of type bool. Would you go about creating 10 output structs to solve that? Or would you use "out"-parameters? Neither is both elegant and productive. Regards, Björn Morén Stockholm, Sweden

          M H 2 Replies Last reply
          0
          • B bjoernen

            Yes, I use those too, but under protest. ;-) But I still find it counter-productive to be forced to create output structs. Nobody uses input structs, because the C# language handles a collection of input parameters elegantly. In my mind output result values ought to be handled the same way. Lets say you have 10 different methods that each return a result object, but from different classes, for instance Point, Rectangle, ArrayList, etc (some of the framework structs and classes). Lets say you also want to be able to tell if the operation went ok, for all those methods, so you'll need a second output parameter of type bool. Would you go about creating 10 output structs to solve that? Or would you use "out"-parameters? Neither is both elegant and productive. Regards, Björn Morén Stockholm, Sweden

            M Offline
            M Offline
            Marc Clifton
            wrote on last edited by
            #7

            bjoernen wrote: Nobody uses input structs, because the C# language handles a collection of input parameters elegantly. Ah, but I disagree. Input structs are very useful too! For example you can have overloaded constructors that accept different parameters and types. You can set defaults, and do validation. An input struct is a very nice middle layer between the caller and the callee. bjoernen wrote: Lets say you have 10 different methods that each return a result object, but from different classes, for instance Point, Rectangle, ArrayList, etc (some of the framework structs and classes). Lets say you also want to be able to tell if the operation went ok, for all those methods, so you'll need a second output parameter of type bool. Would you go about creating 10 output structs to solve that? Or would you use "out"-parameters? Neither is both elegant and productive. In practice, no. But in theory, if I were to really apply my own rules of programming to myself 100% of the time, then yes, I'd create different structs. And I'd make the methods consistent, so that they return a bool, indicating success (although I suppose throwing an exception is the neuveau way now, blech). IMO, the problem, here, is that for all the cool features of something like Visual Studio, it does very little to help in good implementation. If you had a tool that would automatically create the structs for you, then it would be easy and accepted practice. And then, if you needed to modify the struct, you wouldn't have to fix up 10's or 100's of callers to match the new method signature, or create an abortion of overload methods. Obviously though, there is a line between practical and silly. Unfortunately, there are no good guidelines. The current state of [edit]Computer Science[/edit] is a joke, IMO, but that's another matter. It's just that your question has touched on this subject, which is something I like to get up on my soapbox and rant about. :) Marc Microsoft MVP, Visual C# MyXaml MyXaml Blog

            B 1 Reply Last reply
            0
            • B bjoernen

              One thing that have annoyed me with most languages I've used (including C#) is the problem with returning multiple values from methods. The following works, but is not very neat, and to my opinion is not very readable: a = BiteMe(x, y, z, out b, out c); Look how elegant Lua solves this: a, b, c = BiteMe(x, y, z); And notice how easy you can swap variable values in Lua: a, b = b, a; Maybe something for the C# language design team. Regards, Björn Morén Stockholm, Sweden

              H Offline
              H Offline
              Heath Stewart
              wrote on last edited by
              #8

              C# has nothing to do with it. A single return value is defined in the Common Language Infrastructure, or CLI. This is what defines the Common Intermediate Language (CIL), the Common Language Runtime (CLR), the Common Language System (CLS), and more. C# complies to that specification making it one of many languages that can interoperate with each other through Intermediate Language, or simply IL. To change one you'd have to change the entire specification, and I don't see that happening.

              Microsoft MVP, Visual C# My Articles

              B 1 Reply Last reply
              0
              • B bjoernen

                Yes, I use those too, but under protest. ;-) But I still find it counter-productive to be forced to create output structs. Nobody uses input structs, because the C# language handles a collection of input parameters elegantly. In my mind output result values ought to be handled the same way. Lets say you have 10 different methods that each return a result object, but from different classes, for instance Point, Rectangle, ArrayList, etc (some of the framework structs and classes). Lets say you also want to be able to tell if the operation went ok, for all those methods, so you'll need a second output parameter of type bool. Would you go about creating 10 output structs to solve that? Or would you use "out"-parameters? Neither is both elegant and productive. Regards, Björn Morén Stockholm, Sweden

                H Offline
                H Offline
                Heath Stewart
                wrote on last edited by
                #9

                And structs are allocated on the stack, making them excellent for short-time use. A collection is a reference type and is allocated on the heap. The GC will get around to collecting it when it sees fit (and you should rarely force the GC through GC.Collect because it's a synchronous operation). That's a big waste for passing parameter data that is used within the method call and for nothing else (potentially).

                Microsoft MVP, Visual C# My Articles

                1 Reply Last reply
                0
                • M Marc Clifton

                  bjoernen wrote: Nobody uses input structs, because the C# language handles a collection of input parameters elegantly. Ah, but I disagree. Input structs are very useful too! For example you can have overloaded constructors that accept different parameters and types. You can set defaults, and do validation. An input struct is a very nice middle layer between the caller and the callee. bjoernen wrote: Lets say you have 10 different methods that each return a result object, but from different classes, for instance Point, Rectangle, ArrayList, etc (some of the framework structs and classes). Lets say you also want to be able to tell if the operation went ok, for all those methods, so you'll need a second output parameter of type bool. Would you go about creating 10 output structs to solve that? Or would you use "out"-parameters? Neither is both elegant and productive. In practice, no. But in theory, if I were to really apply my own rules of programming to myself 100% of the time, then yes, I'd create different structs. And I'd make the methods consistent, so that they return a bool, indicating success (although I suppose throwing an exception is the neuveau way now, blech). IMO, the problem, here, is that for all the cool features of something like Visual Studio, it does very little to help in good implementation. If you had a tool that would automatically create the structs for you, then it would be easy and accepted practice. And then, if you needed to modify the struct, you wouldn't have to fix up 10's or 100's of callers to match the new method signature, or create an abortion of overload methods. Obviously though, there is a line between practical and silly. Unfortunately, there are no good guidelines. The current state of [edit]Computer Science[/edit] is a joke, IMO, but that's another matter. It's just that your question has touched on this subject, which is something I like to get up on my soapbox and rant about. :) Marc Microsoft MVP, Visual C# MyXaml MyXaml Blog

                  B Offline
                  B Offline
                  bjoernen
                  wrote on last edited by
                  #10

                  Marc Clifton wrote: Ah, but I disagree. Input structs are very useful too! For example you can have overloaded constructors that accept different parameters and types. You can set defaults, and do validation. An input struct is a very nice middle layer between the caller and the callee. I've done projects using both designs (simple parameters vs input structs), and I can't see the advantage of input structs. Input structs are usually very specific; they are used for a specific method. Since all mechanisms you describe can be accomplished with/within methods too (overloaded methods and validation inside methods, etc), I see no use of encapsulating the call parameters, just for sake of encapsulation. Some people argue that it is easier extend the design by adding a parameter to the struct, than it is to the method signature. Just because of this, I would say it tampers with readability. I'll have to look at both method signature and struct to understand how to call this method. I would say that a method should accept a struct only if the struct exists on it's own merits. For instance, it makes no sense to send x, y, width and height when Rectangle exists. Marc Clifton wrote: If you had a tool that would automatically create the structs for you, then it would be easy and accepted practice. And then, if you needed to modify the struct, you wouldn't have to fix up 10's or 100's of callers to match the new method signature, or create an abortion of overload methods I agree that such tool would be very valuable. But I cant see why for example adding a property to a struct (which gets a default value so it wont break 100 callers) is less work than adding an overloaded method that takes another parameter to the class. The lack of support for optional method parameters in C# is another issue. Marc Clifton wrote: The current state of [edit]Computer Science[/edit] is a joke, IMO, but that's another matter. It's just that your question has touched on this subject, which is something I like to get up on my soapbox and rant about. I was pleasantly surprised with the whole .NET initiative at first, and I have to say that C# is a good improvement over Java, and a huge over C++. I will definately stick with it. But I would have liked to see a bigger "generation leap". Especially on the algorithms and patterns department. What we got is a consitent win API, fancier tools and a few new ones. We still code apps the same way.

                  1 Reply Last reply
                  0
                  • H Heath Stewart

                    C# has nothing to do with it. A single return value is defined in the Common Language Infrastructure, or CLI. This is what defines the Common Intermediate Language (CIL), the Common Language Runtime (CLR), the Common Language System (CLS), and more. C# complies to that specification making it one of many languages that can interoperate with each other through Intermediate Language, or simply IL. To change one you'd have to change the entire specification, and I don't see that happening.

                    Microsoft MVP, Visual C# My Articles

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

                    Since out parameters exist, I can't see why Lua-style multiple return values would be difficult to implement in the C# language. In it's rude form it could translate Lua-style method return syntax to the "out"-syntax. Calling: int a; int b; int c; a, b, c = BiteMe(x, y, z); before compilation translates to -> int a; int b; int c; BiteMe(x, y, z, out a, out b, out c); Declaring: public int a, int b, int c BiteMe(int x, int y, int z) { return x, y, z; } before compilation translates to -> public void BiteMe(int x, int y, int z, out int a, out int b, out int c) { a = x; b = y; c = z; } Regards, Björn Morén Stockholm, Sweden

                    1 Reply Last reply
                    0
                    • B bjoernen

                      One thing that have annoyed me with most languages I've used (including C#) is the problem with returning multiple values from methods. The following works, but is not very neat, and to my opinion is not very readable: a = BiteMe(x, y, z, out b, out c); Look how elegant Lua solves this: a, b, c = BiteMe(x, y, z); And notice how easy you can swap variable values in Lua: a, b = b, a; Maybe something for the C# language design team. Regards, Björn Morén Stockholm, Sweden

                      M Offline
                      M Offline
                      MilesAhead
                      wrote on last edited by
                      #12

                      Python allows similar multiple function returns and assignments. As the Python developers will tell you, they are mearly implemented as "syntactic sugar." There's no need for such to bleed down to the lower implementation level in this case either. I've only been messing with C# for a short time but since I tend to use a lot of Win32 API calls more than multiple assignment I'd find useful a tool where I could put the cursor on one of those all caps DEFINES and have it paste in a const with the correct value from one of the Windows.h includes. Hunting that stuff down and typing in const declarations is the pits! :) What a waste of time!

                      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