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. The Lounge
  3. I have a horrible feeling I've been using a pattern for years...

I have a horrible feeling I've been using a pattern for years...

Scheduled Pinned Locked Moved The Lounge
comregextutorialquestionlearning
43 Posts 20 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.
  • OriginalGriffO OriginalGriff

    I use this when the instances are going to be resource heavy - maybe have a couple of images in them - and / or I want one example of each instance through the whole system. So I have a private constructor, a static Dictionary containing all created instances, and a static method which fetches the instance:

    private static Dictionary all = new Dictionary();
    private MyClass(string name, List data )
    {
    ...
    all.Add(name, this);
    }
    public static MyClass Get(string name, List data)
    {
    if (all.ContainsKey(name)) return all[name];
    return new MyClass(name, data);
    }

    And it works really well. But ... is that a pattern? I hope not, I might have to stop using it ... :~

    Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

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

    Yes, it's called the "static cling" pattern as nothing put into the dictionary ever gets garbage collected. ;)

    Latest Article - Class-less Coding - Minimalist C# and Why F# and Function Programming Has Some Advantages Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny Artificial intelligence is the only remedy for natural stupidity. - CDP1802

    C B 2 Replies Last reply
    0
    • D Duncan Edwards Jones

      It is the Tinder pattern. (A collection of singletons)

      J Offline
      J Offline
      Jeremy Falcon
      wrote on last edited by
      #22

      Boom! You sir, have won the Internet today. :laugh:

      Jeremy Falcon

      1 Reply Last reply
      0
      • OriginalGriffO OriginalGriff

        I use this when the instances are going to be resource heavy - maybe have a couple of images in them - and / or I want one example of each instance through the whole system. So I have a private constructor, a static Dictionary containing all created instances, and a static method which fetches the instance:

        private static Dictionary all = new Dictionary();
        private MyClass(string name, List data )
        {
        ...
        all.Add(name, this);
        }
        public static MyClass Get(string name, List data)
        {
        if (all.ContainsKey(name)) return all[name];
        return new MyClass(name, data);
        }

        And it works really well. But ... is that a pattern? I hope not, I might have to stop using it ... :~

        Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

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

        OriginalGriff wrote:

        So I have a private constructor, a static Dictionary containing all created instances, and a static method which fetches the instance:

        I only see a downside

        you create an "instance" and fill it with data // no problems
        ...
        later fetch your "instanse" and do the work // ...wow, that went pretty quick

        all you've done is taken away the ability of the code editor/compiler to check the item exists and built in another opportunity for a hard to find run-time problem. (if you missed it check the spelling, because the compiler wont do that for you.) and the upside isn't there, a separately declared list left empty takes few resoures.

        Installing Signature... Do not switch off your computer.

        1 Reply Last reply
        0
        • OriginalGriffO OriginalGriff

          I use this when the instances are going to be resource heavy - maybe have a couple of images in them - and / or I want one example of each instance through the whole system. So I have a private constructor, a static Dictionary containing all created instances, and a static method which fetches the instance:

          private static Dictionary all = new Dictionary();
          private MyClass(string name, List data )
          {
          ...
          all.Add(name, this);
          }
          public static MyClass Get(string name, List data)
          {
          if (all.ContainsKey(name)) return all[name];
          return new MyClass(name, data);
          }

          And it works really well. But ... is that a pattern? I hope not, I might have to stop using it ... :~

          Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

          C Offline
          C Offline
          CodeWraith
          wrote on last edited by
          #24

          OriginalGriff wrote:

          I hope not, I might have to stop using it ... :~

          Bullshit! :-) Design patterns were never intended to be the last word and the answer for everything. There is no law against coming up with your very own way of doing something, no matter what some gurus want to have you believe. The SOLID faction would condemn you for breaching the single responsibility principle and using something akin to global variables and singletons. So what? My personal sin is a message broker that I use in almost any UI. When compared to awkward wasteful automatic routing in a large UI tree or fragile code bloating manual routing, having a message broker as a singleton is a blessing. Some object registers with the broker to be notified when a specific message is sent, another object sends the message at some time and the broker looks up all subscribers and calls their event handlers. This is reasonably fast (no searching the entire UI tree) and absolutely unproblematic. The only weak spot is that an object better unregister its subscriptions when it is being destroyed, otherwise the broker may get bogged down servicing dead subscriptions. Yes, global variables or singletons may be problematic, but sometimes you can have all of the benefits without any complications. I would immediately redesign if any complications materialized, but not simply for the purity of some design philosophy's sake. Why throw away something that has proven itself to be useful often enough? But that's just me. I have always been conservative with redesigning and been building libraries, even when that meant to store machine code routines on cassette tapes and manually relocating them into a new program.

          I have lived with several Zen masters - all of them were cats.

          1 Reply Last reply
          0
          • M Marc Clifton

            Yes, it's called the "static cling" pattern as nothing put into the dictionary ever gets garbage collected. ;)

            Latest Article - Class-less Coding - Minimalist C# and Why F# and Function Programming Has Some Advantages Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny Artificial intelligence is the only remedy for natural stupidity. - CDP1802

            C Offline
            C Offline
            CodeWraith
            wrote on last edited by
            #25

            Global variables of any flavor have that problem, that's why I would only do something like that for things that remain mostly constant throughout the program's lifetime. Remember the Win32 hInstance parameter? It was passed to WinMain() as a parameter and remained unchanged from then on and you needed it for many Win32 API calls. The four bytes for a global variable were not much of a problem (yes, it was memory that was not cleaned up until the program ended) and it sure beats passing around that value to every window and dialog. When memory hogging is under control, state is not problematic (or even constant), and when I need it all over the place, I will not go through the trouble of routing that object or variable to the remotest parts of the application.

            I have lived with several Zen masters - all of them were cats.

            1 Reply Last reply
            0
            • OriginalGriffO OriginalGriff

              I use this when the instances are going to be resource heavy - maybe have a couple of images in them - and / or I want one example of each instance through the whole system. So I have a private constructor, a static Dictionary containing all created instances, and a static method which fetches the instance:

              private static Dictionary all = new Dictionary();
              private MyClass(string name, List data )
              {
              ...
              all.Add(name, this);
              }
              public static MyClass Get(string name, List data)
              {
              if (all.ContainsKey(name)) return all[name];
              return new MyClass(name, data);
              }

              And it works really well. But ... is that a pattern? I hope not, I might have to stop using it ... :~

              Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

              Mike HankeyM Offline
              Mike HankeyM Offline
              Mike Hankey
              wrote on last edited by
              #26

              A behavioral pattern?

              Someone's therapist knows all about you!

              1 Reply Last reply
              0
              • L Lost User

                OriginalGriff wrote:

                Because most patterns are a waste of time, but worshipped as the One True Holy Grail of Computing by those that learn it. And then force all applications they write to fit that pattern regardless of the appropriateness.

                ..you are interacting with the wrong kind of people. Regardless of your silver bullet, I will not follow in the procession. "Most patterns"? Which are you referring to? They're used throughout the .NET Framework, from factories and adapters to decorators. Just my favourite, the memento, isn't included (afaik, which doesn't mean much). A pattern is simply a formalized piece of code that solves a problem. You have a list of those in your intellisense, don't you? Those snippets are formalized pieces of code that follow a specific pattern and that have a name. Now how does one take one of those templated pieces of code and make a holy grail of it? Is it some consultant, yammering to implement an event-receiver in C#? Code needs to be kissable clean; no patterns "just" to show of that you know something, the simplest solution is always the preferred one. But please, do follow the pattern of wrapping your connections and commands in a using-clause, do use parameterized queries, and please, use the factory-method that is included in the connection object to create your command. It saves a lot of time when rewriting to another provider. ..maybe I should just put my rambling in an article, as a lot of devs that I respect are not too fond of patterns for some weird reason. Tell me, do you vary your code to show a form, or does that happen to be another unnamed pattern that you repeat? :rolleyes:

                Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

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

                Eddy Vluggen wrote:

                maybe I should just put my rambling in an article, as a lot of devs that I respect are not too fond of patterns

                I am sure I would learn something valuable, if you did !

                «While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it.» Claude Levi-Strauss (Tristes Tropiques, 1955)

                L 1 Reply Last reply
                0
                • OriginalGriffO OriginalGriff

                  I use this when the instances are going to be resource heavy - maybe have a couple of images in them - and / or I want one example of each instance through the whole system. So I have a private constructor, a static Dictionary containing all created instances, and a static method which fetches the instance:

                  private static Dictionary all = new Dictionary();
                  private MyClass(string name, List data )
                  {
                  ...
                  all.Add(name, this);
                  }
                  public static MyClass Get(string name, List data)
                  {
                  if (all.ContainsKey(name)) return all[name];
                  return new MyClass(name, data);
                  }

                  And it works really well. But ... is that a pattern? I hope not, I might have to stop using it ... :~

                  Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

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

                  Interesting, Griff, I've played with some similar patterns. It probably was not your intent to show all of your code, but your mention of "heavy resources" made me wonder if you implement IDisposable, or the newer CLassName~ finalizer thingee.

                  «While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it.» Claude Levi-Strauss (Tristes Tropiques, 1955)

                  OriginalGriffO 1 Reply Last reply
                  0
                  • D Duncan Edwards Jones

                    It is the Tinder pattern. (A collection of singletons)

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

                    Duncan Edwards Jones wrote:

                    the Tinder pattern

                    That's a very tricky one since you have to implement your own MultiTassking, and MultiBedding.

                    «While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it.» Claude Levi-Strauss (Tristes Tropiques, 1955)

                    1 Reply Last reply
                    0
                    • B BillWoodruff

                      Interesting, Griff, I've played with some similar patterns. It probably was not your intent to show all of your code, but your mention of "heavy resources" made me wonder if you implement IDisposable, or the newer CLassName~ finalizer thingee.

                      «While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it.» Claude Levi-Strauss (Tristes Tropiques, 1955)

                      OriginalGriffO Offline
                      OriginalGriffO Offline
                      OriginalGriff
                      wrote on last edited by
                      #30

                      IDisposable - and needless to say there are ways to remove items from the all collection to prevent things gumming up the garbage collector.

                      Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                      1 Reply Last reply
                      0
                      • B BillWoodruff

                        Eddy Vluggen wrote:

                        maybe I should just put my rambling in an article, as a lot of devs that I respect are not too fond of patterns

                        I am sure I would learn something valuable, if you did !

                        «While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it.» Claude Levi-Strauss (Tristes Tropiques, 1955)

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

                        Yes, 10 novel ways to obfuscate your code and get a higher LOC :rolleyes: Working on it, and trying to make it usefull, instead of another summary on which pattern does what and whether it is creational or recriational.

                        Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                        1 Reply Last reply
                        0
                        • M Marc Clifton

                          Yes, it's called the "static cling" pattern as nothing put into the dictionary ever gets garbage collected. ;)

                          Latest Article - Class-less Coding - Minimalist C# and Why F# and Function Programming Has Some Advantages Learning to code with python is like learning to swim with those little arm floaties. It gives you undeserved confidence and will eventually drown you. - DangerBunny Artificial intelligence is the only remedy for natural stupidity. - CDP1802

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

                          Marc Clifton wrote:

                          nothing put into the dictionary ever gets garbage collected.

                          Is there no way to handle that >?

                          «While I complain of being able to see only a shadow of the past, I may be insensitive to reality as it is now, since I'm not at a stage of development where I'm capable of seeing it.» Claude Levi-Strauss (Tristes Tropiques, 1955)

                          1 Reply Last reply
                          0
                          • L Lost User

                            OriginalGriff wrote:

                            Because most patterns are a waste of time, but worshipped as the One True Holy Grail of Computing by those that learn it. And then force all applications they write to fit that pattern regardless of the appropriateness.

                            ..you are interacting with the wrong kind of people. Regardless of your silver bullet, I will not follow in the procession. "Most patterns"? Which are you referring to? They're used throughout the .NET Framework, from factories and adapters to decorators. Just my favourite, the memento, isn't included (afaik, which doesn't mean much). A pattern is simply a formalized piece of code that solves a problem. You have a list of those in your intellisense, don't you? Those snippets are formalized pieces of code that follow a specific pattern and that have a name. Now how does one take one of those templated pieces of code and make a holy grail of it? Is it some consultant, yammering to implement an event-receiver in C#? Code needs to be kissable clean; no patterns "just" to show of that you know something, the simplest solution is always the preferred one. But please, do follow the pattern of wrapping your connections and commands in a using-clause, do use parameterized queries, and please, use the factory-method that is included in the connection object to create your command. It saves a lot of time when rewriting to another provider. ..maybe I should just put my rambling in an article, as a lot of devs that I respect are not too fond of patterns for some weird reason. Tell me, do you vary your code to show a form, or does that happen to be another unnamed pattern that you repeat? :rolleyes:

                            Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                            K Offline
                            K Offline
                            killbot5000
                            wrote on last edited by
                            #33

                            I don't care for patterns in my code and I definitely don't care for vague terms like "clean" code. I only care for code that's short, safe to fail, easy to test, and understandable by a college freshman in less than 2 weeks. Nevertheless, please write about the patterns you think are worthwhile; preferably with a not-too-generic example. You might teach us something worthwhile. Also, if anyone knows of a must-read regarding the use of factory-pattern, please share. I really hate it and I'm looking for material to nuance my feelings towards it.

                            L 2 Replies Last reply
                            0
                            • OriginalGriffO OriginalGriff

                              I use this when the instances are going to be resource heavy - maybe have a couple of images in them - and / or I want one example of each instance through the whole system. So I have a private constructor, a static Dictionary containing all created instances, and a static method which fetches the instance:

                              private static Dictionary all = new Dictionary();
                              private MyClass(string name, List data )
                              {
                              ...
                              all.Add(name, this);
                              }
                              public static MyClass Get(string name, List data)
                              {
                              if (all.ContainsKey(name)) return all[name];
                              return new MyClass(name, data);
                              }

                              And it works really well. But ... is that a pattern? I hope not, I might have to stop using it ... :~

                              Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                              D Offline
                              D Offline
                              Dave Sexton
                              wrote on last edited by
                              #34

                              Seems like an Appalachian version of DI, just missing a banjo duel :)

                              But fortunately we have the nanny-state politicians who can step in to protect us poor stupid consumers, most of whom would not know a JVM from a frozen chicken. Bruce Pierson
                              Because programming is an art, not a science. Marc Clifton
                              I gave up when I couldn't spell "egg". Justine Allen

                              1 Reply Last reply
                              0
                              • K killbot5000

                                I don't care for patterns in my code and I definitely don't care for vague terms like "clean" code. I only care for code that's short, safe to fail, easy to test, and understandable by a college freshman in less than 2 weeks. Nevertheless, please write about the patterns you think are worthwhile; preferably with a not-too-generic example. You might teach us something worthwhile. Also, if anyone knows of a must-read regarding the use of factory-pattern, please share. I really hate it and I'm looking for material to nuance my feelings towards it.

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

                                killbot5000 wrote:

                                understandable by a college freshman in less than 2 weeks.

                                If you can't explain your pattern in 5 minutes time, then you probably don't understand it. That is assuming that your freshman knows how to code :)

                                killbot5000 wrote:

                                Also, if anyone knows of a must-read regarding the use of factory-pattern, please share.

                                That's the pattern I'm opening the article with. May take another day or two.

                                killbot5000 wrote:

                                I really hate it

                                Yah, then you had the wrong explanation. Most important question to answer is always "what's in it for me?", and a factory has an easy to explain benefit :thumbsup:

                                Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                                K 1 Reply Last reply
                                0
                                • OriginalGriffO OriginalGriff

                                  I use this when the instances are going to be resource heavy - maybe have a couple of images in them - and / or I want one example of each instance through the whole system. So I have a private constructor, a static Dictionary containing all created instances, and a static method which fetches the instance:

                                  private static Dictionary all = new Dictionary();
                                  private MyClass(string name, List data )
                                  {
                                  ...
                                  all.Add(name, this);
                                  }
                                  public static MyClass Get(string name, List data)
                                  {
                                  if (all.ContainsKey(name)) return all[name];
                                  return new MyClass(name, data);
                                  }

                                  And it works really well. But ... is that a pattern? I hope not, I might have to stop using it ... :~

                                  Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                                  G Offline
                                  G Offline
                                  Gary Wheeler
                                  wrote on last edited by
                                  #36

                                  Hmm. I don't see anything wrong with it, other than the name "all" for the container, which isn't terribly descriptive. I've used similar "patterns", where constructors and destructors maintain global constructs as a side effect. The global constructs usually simplify finding one of the instances in some way, or in accessing the entire collection of 'live' instances. In some cases I also use them for orderly shutdowns, to insure that all instances get destroyed properly. For what it's worth, I've never read the GoF Patterns book.

                                  Software Zen: delete this;

                                  1 Reply Last reply
                                  0
                                  • OriginalGriffO OriginalGriff

                                    I use this when the instances are going to be resource heavy - maybe have a couple of images in them - and / or I want one example of each instance through the whole system. So I have a private constructor, a static Dictionary containing all created instances, and a static method which fetches the instance:

                                    private static Dictionary all = new Dictionary();
                                    private MyClass(string name, List data )
                                    {
                                    ...
                                    all.Add(name, this);
                                    }
                                    public static MyClass Get(string name, List data)
                                    {
                                    if (all.ContainsKey(name)) return all[name];
                                    return new MyClass(name, data);
                                    }

                                    And it works really well. But ... is that a pattern? I hope not, I might have to stop using it ... :~

                                    Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

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

                                    Shoulda used a concurrent dictionary...

                                    "(I) am amazed to see myself here rather than there ... now rather than then". ― Blaise Pascal

                                    1 Reply Last reply
                                    0
                                    • OriginalGriffO OriginalGriff

                                      Because most patterns are a waste of time, but worshipped as the One True Holy Grail of Computing by those that learn it. And then force all applications they write to fit that pattern regardless of the appropriateness.

                                      Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                                      K Offline
                                      K Offline
                                      Kirk 10389821
                                      wrote on last edited by
                                      #38

                                      I was really wondering why you did not want to use a pattern so badly you would strike it from your code. I bought the GoF book, and was excited to be able to communicate better designs quicker. But, like you, I found zealots who used patterns like an indentation style. The could not code without them, and would convolute a simple program with them. I moved away from them, but use patterns (factory, most often) where they are clearly a solid approach, but NEVER worrying about doing it exactly as prescribed. But your comment felt like "I refuse to indent my code because there are indentation extremists"...

                                      1 Reply Last reply
                                      0
                                      • OriginalGriffO OriginalGriff

                                        I use this when the instances are going to be resource heavy - maybe have a couple of images in them - and / or I want one example of each instance through the whole system. So I have a private constructor, a static Dictionary containing all created instances, and a static method which fetches the instance:

                                        private static Dictionary all = new Dictionary();
                                        private MyClass(string name, List data )
                                        {
                                        ...
                                        all.Add(name, this);
                                        }
                                        public static MyClass Get(string name, List data)
                                        {
                                        if (all.ContainsKey(name)) return all[name];
                                        return new MyClass(name, data);
                                        }

                                        And it works really well. But ... is that a pattern? I hope not, I might have to stop using it ... :~

                                        Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                                        J Offline
                                        J Offline
                                        jschell
                                        wrote on last edited by
                                        #39

                                        OriginalGriff wrote:

                                        And it works really well. But ... is that a pattern?

                                        Yes. Multiton. Been around a long time. Multiton pattern - Wikipedia[^] The general idea is a Singleton per 'context' where the definition of the context is up the implementation.

                                        1 Reply Last reply
                                        0
                                        • OriginalGriffO OriginalGriff

                                          I use this when the instances are going to be resource heavy - maybe have a couple of images in them - and / or I want one example of each instance through the whole system. So I have a private constructor, a static Dictionary containing all created instances, and a static method which fetches the instance:

                                          private static Dictionary all = new Dictionary();
                                          private MyClass(string name, List data )
                                          {
                                          ...
                                          all.Add(name, this);
                                          }
                                          public static MyClass Get(string name, List data)
                                          {
                                          if (all.ContainsKey(name)) return all[name];
                                          return new MyClass(name, data);
                                          }

                                          And it works really well. But ... is that a pattern? I hope not, I might have to stop using it ... :~

                                          Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                                          Richard DeemingR Offline
                                          Richard DeemingR Offline
                                          Richard Deeming
                                          wrote on last edited by
                                          #40

                                          A cunning way of asking a programming question in the Lounge! ;P The all field should be readonly, since you never replace it. You should probably specify an explicit StringComparer for the dictionary, to make it more obvious that the key is case-sensitive. I'd be inclined to move the Add to the static method, and leave the constructor alone. I'd also replace the ContainsKey / indexer pair with a single TryGetValue call:

                                          public static MyClass Get(string name, List<string> data)
                                          {
                                          if (!all.TryGetValue(name, out MyClass instance)
                                          {
                                          instance = new MyClass(name, data);
                                          all.Add(name, instance);
                                          }

                                          return instance;
                                          

                                          }

                                          And as Gerry said, if there's any possibility of the method being called by multiple threads, use a ConcurrentDictionary[^] instead:

                                          private static readonly ConcurrentDictionary<string, MyClass> all = new ConcurrentDictionary<string, MyClass>(StringComparer.Ordinal);

                                          public static MyClass Get(string name, List<string> data)
                                          {
                                          return all.GetOrAdd(name, key => new MyClass(key, data));
                                          }

                                          Let's hope your class doesn't contain any unmanaged or disposable resources, since you'd have no way of knowing when to clean them up. :-D


                                          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                                          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