0

I'm working on a personal project and decided to try to save some methods I'll continue to use for other projects to their own namespace, to be imported into files as needed.

namespace MyUtils
{
    namespace Cards
    {
        public class Cards
        {
            public void Shuffle(List<int> deck)
            {
                //shuffles the given deck
            }
        }
    }
}

My goal is to set it up so that I don't have to import all of my methods into a file or program every time, so with the nested namespace I'm able to use using MyUtils.Cards to just import the Cards methods without needing to bring in every other method that may not be needed for a given project.

Now in my Program file, the only way I've gotten this to work is to create an object Cards c = new Cards() and then call c.Shuffle(list);. Is there a way I can set this up where I can call the Shuffle method without having to create a Cards object? Ideally, I'd like to be able to just create a List and then call Shuffle(list), but I can't figure out how to do so.

My first thought was to move the Shuffle method out of the Cards class and into the Cards namespace block, but it seems that methods can't go directly into namespaces. If this can't be done with namespaces and using, is there another way I could create a set of methods and store them in a way where they can be reused in multiple programs?

  • 2
    If the method isn't `static`, then you need to instantiate an object of the containing type. Do you know about, or can you use static methods? – gunr2171 May 19 '23 at 02:16
  • Think about methods like `MessageBox.Show` and `File.ReadAllLines`. They are called on the class rather than an instance of the class because they are declared `static`, as suggested above. If you declare the class itself `static` then every member of that class must also be `static`. – jmcilhinney May 19 '23 at 02:29
  • Ah, that works! Thanks @gunr2171 and @jmcilhinney I'd had a hard time understanding the `static` keyword, but implementing it and seeing how it works in my code is helping it click for me. – Donnervogel May 19 '23 at 02:51
  • But, if a Cards object represents a group of cards, say 52 of them, broken into 4 groups of 13, then creating the deck in the constructor and shuffling it in an instance method makes a lot of sense. Read up on how "object orientation and design" works – Flydog57 May 19 '23 at 03:55
  • did you ever search here on SO for *c# shuffle list*? – Sir Rufo May 19 '23 at 04:47

0 Answers0