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. How to return a collection from a method.

How to return a collection from a method.

Scheduled Pinned Locked Moved C#
tutorialquestion
14 Posts 9 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.
  • C Offline
    C Offline
    Chiman1
    wrote on last edited by
    #1

    public List<string> GetList()
    {
    List<string> list = new List<string>();
    return list;
    }

    But as per msdn we should not expose the generic list. How to return a list from a method. 2) Simillarly I have a method which has dictionary as a return type How to return a dictionary from a method. 3) In my code I have craeted a dictionary as

    Dictionary < int , Some Str>

    . Now I need a colletion of keys avaialble in the dictionary. How to do this.?? Do I need to retrive one by on from dictionary. ??

    L N C realJSOPR D 6 Replies Last reply
    0
    • C Chiman1

      public List<string> GetList()
      {
      List<string> list = new List<string>();
      return list;
      }

      But as per msdn we should not expose the generic list. How to return a list from a method. 2) Simillarly I have a method which has dictionary as a return type How to return a dictionary from a method. 3) In my code I have craeted a dictionary as

      Dictionary < int , Some Str>

      . Now I need a colletion of keys avaialble in the dictionary. How to do this.?? Do I need to retrive one by on from dictionary. ??

      L Offline
      L Offline
      Luc Pattyn
      wrote on last edited by
      #2

      Hi, 1. there is nothing that prevents you from returning a List (or any other collection) like that. There may be "good practice" or "OO" reasons not to do so under certain circumstances, but it is perfect C#. 2. see 1. 3. if you look through the MSDN documentation, more particularly the properties of Dictionary<Tkey, Tvalue>, you will notice it is all there. :)

      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


      I only read formatted code with indentation, so please use PRE tags for code snippets.


      I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


      1 Reply Last reply
      0
      • C Chiman1

        public List<string> GetList()
        {
        List<string> list = new List<string>();
        return list;
        }

        But as per msdn we should not expose the generic list. How to return a list from a method. 2) Simillarly I have a method which has dictionary as a return type How to return a dictionary from a method. 3) In my code I have craeted a dictionary as

        Dictionary < int , Some Str>

        . Now I need a colletion of keys avaialble in the dictionary. How to do this.?? Do I need to retrive one by on from dictionary. ??

        N Offline
        N Offline
        Not Active
        wrote on last edited by
        #3

        FxCop will recommend using ReadOnlyCollection[^]


        I know the language. I've read a book. - _Madmatt

        realJSOPR 1 Reply Last reply
        0
        • C Chiman1

          public List<string> GetList()
          {
          List<string> list = new List<string>();
          return list;
          }

          But as per msdn we should not expose the generic list. How to return a list from a method. 2) Simillarly I have a method which has dictionary as a return type How to return a dictionary from a method. 3) In my code I have craeted a dictionary as

          Dictionary < int , Some Str>

          . Now I need a colletion of keys avaialble in the dictionary. How to do this.?? Do I need to retrive one by on from dictionary. ??

          C Offline
          C Offline
          carbon_golem
          wrote on last edited by
          #4

          Try using a custom iterator. Passing back a generic list is wasteful in some cases anyway.

          public IEnumerable<String> GetStrings(){
          foreach(var str in stringList){
          yield return str;
          }
          }

          "Simplicity carried to the extreme becomes elegance."
          -Jon Franklin

          1 Reply Last reply
          0
          • N Not Active

            FxCop will recommend using ReadOnlyCollection[^]


            I know the language. I've read a book. - _Madmatt

            realJSOPR Offline
            realJSOPR Offline
            realJSOP
            wrote on last edited by
            #5

            That seems kind of inefficient. Does that mean there are now two copies of the same data in memory? (Actually, with their crappy sample, the array at the end of the Main() method makes a 3rd copy).

            .45 ACP - because shooting twice is just silly
            -----
            "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
            -----
            "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

            modified on Wednesday, June 9, 2010 1:50 PM

            N L 2 Replies Last reply
            0
            • C Chiman1

              public List<string> GetList()
              {
              List<string> list = new List<string>();
              return list;
              }

              But as per msdn we should not expose the generic list. How to return a list from a method. 2) Simillarly I have a method which has dictionary as a return type How to return a dictionary from a method. 3) In my code I have craeted a dictionary as

              Dictionary < int , Some Str>

              . Now I need a colletion of keys avaialble in the dictionary. How to do this.?? Do I need to retrive one by on from dictionary. ??

              realJSOPR Offline
              realJSOPR Offline
              realJSOP
              wrote on last edited by
              #6

              You can do it that way (and IMHO, if the compiler lets you do it, nobody else has the right to complain, coding style guidelines in force not withstanding), but to ease typing, I create a class derived from the desired collection type:

              public class ListOfThings : List<Thing>{}

              That way, I can pass/return a ListOfThings object instead of having to type all that crap over and over again.

              public ListOfThings GetListOfThings() { get; set; }

              I can also add custom methods to the class that perform Thing-specific functionality.

              .45 ACP - because shooting twice is just silly
              -----
              "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
              -----
              "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

              A 1 Reply Last reply
              0
              • realJSOPR realJSOP

                That seems kind of inefficient. Does that mean there are now two copies of the same data in memory? (Actually, with their crappy sample, the array at the end of the Main() method makes a 3rd copy).

                .45 ACP - because shooting twice is just silly
                -----
                "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                -----
                "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                modified on Wednesday, June 9, 2010 1:50 PM

                N Offline
                N Offline
                Not Active
                wrote on last edited by
                #7

                :omg: You're not supposed to actually read or use the examples ;P


                I know the language. I've read a book. - _Madmatt

                1 Reply Last reply
                0
                • C Chiman1

                  public List<string> GetList()
                  {
                  List<string> list = new List<string>();
                  return list;
                  }

                  But as per msdn we should not expose the generic list. How to return a list from a method. 2) Simillarly I have a method which has dictionary as a return type How to return a dictionary from a method. 3) In my code I have craeted a dictionary as

                  Dictionary < int , Some Str>

                  . Now I need a colletion of keys avaialble in the dictionary. How to do this.?? Do I need to retrive one by on from dictionary. ??

                  D Offline
                  D Offline
                  dan sh
                  wrote on last edited by
                  #8

                  It is code analysis that tells to return collections in stead of List. You can make use of a global suppression file in your code to get rid of it. For dictionary, it would be suggesting a read only collection. Suppress that too if you do not want another object to be returned. It is up to you to decide till when you are going to follow MS code analysis. I personally follow everything it tells.

                  1 Reply Last reply
                  0
                  • realJSOPR realJSOP

                    You can do it that way (and IMHO, if the compiler lets you do it, nobody else has the right to complain, coding style guidelines in force not withstanding), but to ease typing, I create a class derived from the desired collection type:

                    public class ListOfThings : List<Thing>{}

                    That way, I can pass/return a ListOfThings object instead of having to type all that crap over and over again.

                    public ListOfThings GetListOfThings() { get; set; }

                    I can also add custom methods to the class that perform Thing-specific functionality.

                    .45 ACP - because shooting twice is just silly
                    -----
                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                    -----
                    "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                    A Offline
                    A Offline
                    Andrew Rissing
                    wrote on last edited by
                    #9

                    John Simmons / outlaw programmer wrote:

                    You can do it that way ...

                    But you end up actually typing MORE 'things': ListOfThings List

                    realJSOPR 1 Reply Last reply
                    0
                    • A Andrew Rissing

                      John Simmons / outlaw programmer wrote:

                      You can do it that way ...

                      But you end up actually typing MORE 'things': ListOfThings List

                      realJSOPR Offline
                      realJSOPR Offline
                      realJSOP
                      wrote on last edited by
                      #10

                      List - a little shorter ListOfThings - a little eaiser to read ThingsList - even shorter and still easier to read - WINNER!

                      .45 ACP - because shooting twice is just silly
                      -----
                      "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                      -----
                      "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                      1 Reply Last reply
                      0
                      • realJSOPR realJSOP

                        That seems kind of inefficient. Does that mean there are now two copies of the same data in memory? (Actually, with their crappy sample, the array at the end of the Main() method makes a 3rd copy).

                        .45 ACP - because shooting twice is just silly
                        -----
                        "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                        -----
                        "The staggering layers of obscenity in your statement make it a work of art on so many levels." - J. Jystad, 2001

                        modified on Wednesday, June 9, 2010 1:50 PM

                        L Offline
                        L Offline
                        Luc Pattyn
                        wrote on last edited by
                        #11

                        John Simmons / outlaw programmer wrote:

                        Does that mean there are now two copies

                        No. The way I understand it the ReadOnlyThingy is just a wrapper; it holds a reference to the original collection (and that explains how it tracks the changes to the original collection, see the example), but offers fewer valid operations on that collection. So nothing gets copied. I haven't used it ever yet, as I see not much point in making the collection read-only, while the items in the collection remain as they were, modifiable at will (except for the silly example that used strings of course). :)

                        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                        I only read formatted code with indentation, so please use PRE tags for code snippets.


                        I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                        D 1 Reply Last reply
                        0
                        • L Luc Pattyn

                          John Simmons / outlaw programmer wrote:

                          Does that mean there are now two copies

                          No. The way I understand it the ReadOnlyThingy is just a wrapper; it holds a reference to the original collection (and that explains how it tracks the changes to the original collection, see the example), but offers fewer valid operations on that collection. So nothing gets copied. I haven't used it ever yet, as I see not much point in making the collection read-only, while the items in the collection remain as they were, modifiable at will (except for the silly example that used strings of course). :)

                          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                          I only read formatted code with indentation, so please use PRE tags for code snippets.


                          I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


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

                          I use them quite a lot. Many times I want a collection to be exposed but not have add and remove methods etc as I don't want the collection itself to be modified. I find it very useful!

                          Dave

                          If this helped, please vote & accept answer!

                          Binging is like googling, it just feels dirtier. (Pete O'Hanlon)
                          BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

                          L 1 Reply Last reply
                          0
                          • D DaveyM69

                            I use them quite a lot. Many times I want a collection to be exposed but not have add and remove methods etc as I don't want the collection itself to be modified. I find it very useful!

                            Dave

                            If this helped, please vote & accept answer!

                            Binging is like googling, it just feels dirtier. (Pete O'Hanlon)
                            BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)

                            L Offline
                            L Offline
                            Luc Pattyn
                            wrote on last edited by
                            #13

                            You're probably right, I still have to get used to them... :)

                            Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                            I only read formatted code with indentation, so please use PRE tags for code snippets.


                            I'm not participating in frackin' Q&A, so if you want my opinion, ask away in a real forum (or on my profile page).


                            1 Reply Last reply
                            0
                            • C Chiman1

                              public List<string> GetList()
                              {
                              List<string> list = new List<string>();
                              return list;
                              }

                              But as per msdn we should not expose the generic list. How to return a list from a method. 2) Simillarly I have a method which has dictionary as a return type How to return a dictionary from a method. 3) In my code I have craeted a dictionary as

                              Dictionary < int , Some Str>

                              . Now I need a colletion of keys avaialble in the dictionary. How to do this.?? Do I need to retrive one by on from dictionary. ??

                              S Offline
                              S Offline
                              srng net
                              wrote on last edited by
                              #14

                              Regarding Geneneric list as return type : If you send/return the generic list outside, your collection can be very easily changed from outside of your class without your permission and you lose total control on the same. that is why , one should not expose or return generic list and use ReadOnlyCollection instead. Dot net does not force you to do so but generally its not good programming practice! Regarding point 2 : Here also, A ReadOnlyCollection is recommanded. Regarding point 3 : You can create your customDictionary in which you can maintain and return the colelction of keys and/or collection of values as per request.

                              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