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. Code Puzzler: How quickly can you figure out why this acting "weird"?

Code Puzzler: How quickly can you figure out why this acting "weird"?

Scheduled Pinned Locked Moved The Lounge
helpquestionjavascriptpythonphp
25 Posts 13 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.
  • M Marc Clifton

    0x01AA wrote:

    Do we really Need to write code where we Need first to solve a puzzle to get what the code is doing

    Well, this is different. It's a stupid bug on my part. But it's like language. If you can speak at more than a 3rd grade level, you can express your thoughts better. ;)

    Latest Article - Building a Prototype Web-Based Diagramming Tool with SVG and Javascript 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

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

    Quote:

    If you can speak at more than a 3rd grade level, you can express your thoughts better

    No idea what this means, sounds only I'm undeveloped :sigh: Btw. I'm aware, I'm most probably not able to solve the puzzle

    It does not solve my Problem, but it answers my question

    OriginalGriffO 1 Reply Last reply
    0
    • M Marc Clifton

      And no, this isn't a programming question in the lounge. I started asking this question in the QA forum because it had me totally stumped. As I was filling out the "What I've tried" I had a major :doh: :doh: :doh: :doh: moment. To prove I'm not asking for help on the lounge, I posted a solution on [my blog](https://marcclifton.wordpress.com/2018/05/31/the-fix/). You'll need to use the password "fizbin" as the blog post is specifically for this lounge post and eventually I'll delete the post. It is a fun one though. Here's the code:

      public class ModelDataContext : DataContext
      {
          public static ModelDataContext Context;
      
          public ModelDataContext(DbConnection conn) : base(conn)
          {
              Context = this;
          }
      }
      
      class Program
      {
          static ModelDataContext mdc = new ModelDataContext(new SqlConnection("\[some string\]"));
      
          static void CreateNewContext(DataContext context, out SqlConnection conn, out DataContext newContext)
          {
              conn = new SqlConnection(context.Connection.ConnectionString);
              newContext = (DataContext)Activator.CreateInstance(context.GetType(), new object\[\] { conn });
              Console.WriteLine(context == newContext);
          }
      
          static void Main(string\[\] args)
          {
              SqlConnection conn2;
              DataContext newdc;
              CreateNewContext(ModelDataContext.Context, out conn2, out newdc);
      
              Console.WriteLine(ModelDataContext.Context == newdc);
          }
      }
      

      and the result is: False True Why is the second equality True when the first is False??? And for the bonus prize, what's a fix?

      Latest Article - Building a Prototype Web-Based Diagramming Tool with SVG and Javascript 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

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

      Roughly 90 seconds, mostly working out which Console.WriteLine call was which. :) Spoilers ahead - select the block to view:

      Take a copy of the static field; Create a new instance, thus overwriting the static field; Compare the new instance to the copy of the old value of the static field - result = false; Compare the new instance to the current value of the static field - result = true;

      Damnit Chris, we need a <div class="spoiler">!


      "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

      L M 2 Replies Last reply
      0
      • L Lost User

        Quote:

        If you can speak at more than a 3rd grade level, you can express your thoughts better

        No idea what this means, sounds only I'm undeveloped :sigh: Btw. I'm aware, I'm most probably not able to solve the puzzle

        It does not solve my Problem, but it answers my question

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

        You probably could, with a bit of thinking about it - it's obvious when you see it, but it's a stinker to spot if you didn't write the code (and probably even harder if you did if you are anything like me: I tend to see what I meant to write, rather than what I did :-O )

        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

        Mike HankeyM U 2 Replies Last reply
        0
        • Richard DeemingR Richard Deeming

          Roughly 90 seconds, mostly working out which Console.WriteLine call was which. :) Spoilers ahead - select the block to view:

          Take a copy of the static field; Create a new instance, thus overwriting the static field; Compare the new instance to the copy of the old value of the static field - result = false; Compare the new instance to the current value of the static field - result = true;

          Damnit Chris, we need a <div class="spoiler">!


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

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

          Black in black until I select all the text in the black :-D

          It does not solve my Problem, but it answers my question

          1 Reply Last reply
          0
          • M Marc Clifton

            And no, this isn't a programming question in the lounge. I started asking this question in the QA forum because it had me totally stumped. As I was filling out the "What I've tried" I had a major :doh: :doh: :doh: :doh: moment. To prove I'm not asking for help on the lounge, I posted a solution on [my blog](https://marcclifton.wordpress.com/2018/05/31/the-fix/). You'll need to use the password "fizbin" as the blog post is specifically for this lounge post and eventually I'll delete the post. It is a fun one though. Here's the code:

            public class ModelDataContext : DataContext
            {
                public static ModelDataContext Context;
            
                public ModelDataContext(DbConnection conn) : base(conn)
                {
                    Context = this;
                }
            }
            
            class Program
            {
                static ModelDataContext mdc = new ModelDataContext(new SqlConnection("\[some string\]"));
            
                static void CreateNewContext(DataContext context, out SqlConnection conn, out DataContext newContext)
                {
                    conn = new SqlConnection(context.Connection.ConnectionString);
                    newContext = (DataContext)Activator.CreateInstance(context.GetType(), new object\[\] { conn });
                    Console.WriteLine(context == newContext);
                }
            
                static void Main(string\[\] args)
                {
                    SqlConnection conn2;
                    DataContext newdc;
                    CreateNewContext(ModelDataContext.Context, out conn2, out newdc);
            
                    Console.WriteLine(ModelDataContext.Context == newdc);
                }
            }
            

            and the result is: False True Why is the second equality True when the first is False??? And for the bonus prize, what's a fix?

            Latest Article - Building a Prototype Web-Based Diagramming Tool with SVG and Javascript 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

            P Offline
            P Offline
            PIEBALDconsult
            wrote on last edited by
            #8

            Is it a problem? Does it need to be fixed? :confused: I wouldn't presume to say that you didn't write exactly what you intended. Setting a static on each instantiation is unusual though.

            1 Reply Last reply
            0
            • M Marc Clifton

              And no, this isn't a programming question in the lounge. I started asking this question in the QA forum because it had me totally stumped. As I was filling out the "What I've tried" I had a major :doh: :doh: :doh: :doh: moment. To prove I'm not asking for help on the lounge, I posted a solution on [my blog](https://marcclifton.wordpress.com/2018/05/31/the-fix/). You'll need to use the password "fizbin" as the blog post is specifically for this lounge post and eventually I'll delete the post. It is a fun one though. Here's the code:

              public class ModelDataContext : DataContext
              {
                  public static ModelDataContext Context;
              
                  public ModelDataContext(DbConnection conn) : base(conn)
                  {
                      Context = this;
                  }
              }
              
              class Program
              {
                  static ModelDataContext mdc = new ModelDataContext(new SqlConnection("\[some string\]"));
              
                  static void CreateNewContext(DataContext context, out SqlConnection conn, out DataContext newContext)
                  {
                      conn = new SqlConnection(context.Connection.ConnectionString);
                      newContext = (DataContext)Activator.CreateInstance(context.GetType(), new object\[\] { conn });
                      Console.WriteLine(context == newContext);
                  }
              
                  static void Main(string\[\] args)
                  {
                      SqlConnection conn2;
                      DataContext newdc;
                      CreateNewContext(ModelDataContext.Context, out conn2, out newdc);
              
                      Console.WriteLine(ModelDataContext.Context == newdc);
                  }
              }
              

              and the result is: False True Why is the second equality True when the first is False??? And for the bonus prize, what's a fix?

              Latest Article - Building a Prototype Web-Based Diagramming Tool with SVG and Javascript 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

              J Offline
              J Offline
              Jon McKee
              wrote on last edited by
              #9

              The problem is that you're assigning a static variable inside the instance constructor to that instance . So every time you create an object you're changing the Context property. The reason the tests are different is because you pass the Context as a parameter so even after the update the parameter still has the old Context. A fix would be to not do that because it's bad design ;P I'd make Context an instance property and implement your own ==, !=, Equals, etc unless you want referential equality.

              1 Reply Last reply
              0
              • M Marc Clifton

                And no, this isn't a programming question in the lounge. I started asking this question in the QA forum because it had me totally stumped. As I was filling out the "What I've tried" I had a major :doh: :doh: :doh: :doh: moment. To prove I'm not asking for help on the lounge, I posted a solution on [my blog](https://marcclifton.wordpress.com/2018/05/31/the-fix/). You'll need to use the password "fizbin" as the blog post is specifically for this lounge post and eventually I'll delete the post. It is a fun one though. Here's the code:

                public class ModelDataContext : DataContext
                {
                    public static ModelDataContext Context;
                
                    public ModelDataContext(DbConnection conn) : base(conn)
                    {
                        Context = this;
                    }
                }
                
                class Program
                {
                    static ModelDataContext mdc = new ModelDataContext(new SqlConnection("\[some string\]"));
                
                    static void CreateNewContext(DataContext context, out SqlConnection conn, out DataContext newContext)
                    {
                        conn = new SqlConnection(context.Connection.ConnectionString);
                        newContext = (DataContext)Activator.CreateInstance(context.GetType(), new object\[\] { conn });
                        Console.WriteLine(context == newContext);
                    }
                
                    static void Main(string\[\] args)
                    {
                        SqlConnection conn2;
                        DataContext newdc;
                        CreateNewContext(ModelDataContext.Context, out conn2, out newdc);
                
                        Console.WriteLine(ModelDataContext.Context == newdc);
                    }
                }
                

                and the result is: False True Why is the second equality True when the first is False??? And for the bonus prize, what's a fix?

                Latest Article - Building a Prototype Web-Based Diagramming Tool with SVG and Javascript 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

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

                Just read the blog post, and I don't think your fix will work. :)


                "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

                J 1 Reply Last reply
                0
                • Richard DeemingR Richard Deeming

                  Just read the blog post, and I don't think your fix will work. :)


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

                  J Offline
                  J Offline
                  Jon McKee
                  wrote on last edited by
                  #11

                  It will work in that specific example because he also changed the CreateInstance call to not use conn anymore. But yes, if the parameterized constructor is called it'll still have the same issue :thumbsup:

                  Richard DeemingR 1 Reply Last reply
                  0
                  • J Jon McKee

                    It will work in that specific example because he also changed the CreateInstance call to not use conn anymore. But yes, if the parameterized constructor is called it'll still have the same issue :thumbsup:

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

                    Well, it will "work", in the sense that it won't overwrite the static instance. But it won't work, in the sense that the returned instance will be using the default connection string for the context, not the connection string from the instance passed in. :)


                    "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

                    M 1 Reply Last reply
                    0
                    • Richard DeemingR Richard Deeming

                      Roughly 90 seconds, mostly working out which Console.WriteLine call was which. :) Spoilers ahead - select the block to view:

                      Take a copy of the static field; Create a new instance, thus overwriting the static field; Compare the new instance to the copy of the old value of the static field - result = false; Compare the new instance to the current value of the static field - result = true;

                      Damnit Chris, we need a <div class="spoiler">!


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

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

                      Richard Deeming wrote:

                      select the block to view:

                      Now THAT is snazzy!

                      Latest Article - Building a Prototype Web-Based Diagramming Tool with SVG and Javascript 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

                      1 Reply Last reply
                      0
                      • Richard DeemingR Richard Deeming

                        Well, it will "work", in the sense that it won't overwrite the static instance. But it won't work, in the sense that the returned instance will be using the default connection string for the context, not the connection string from the instance passed in. :)


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

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

                        Richard Deeming wrote:

                        But it won't work, in the sense that the returned instance will be using the default connection string for the context, not the connection string from the instance passed in.

                        Hmm. But the parameterless constructor uses the connection string of the (hopefully) already initialized context: public ModelDataContext() : base(Context.Connection) However, it's a moot point anyways as I refactored the whole mess into something much less weird. It'll be an interesting question though to pose to a couple of the devs at work, though I'll reduce the complexity of it omitting the DataContext base class - it's rather superfluous to the example.

                        Latest Article - Building a Prototype Web-Based Diagramming Tool with SVG and Javascript 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

                        Richard DeemingR 1 Reply Last reply
                        0
                        • M Marc Clifton

                          Richard Deeming wrote:

                          But it won't work, in the sense that the returned instance will be using the default connection string for the context, not the connection string from the instance passed in.

                          Hmm. But the parameterless constructor uses the connection string of the (hopefully) already initialized context: public ModelDataContext() : base(Context.Connection) However, it's a moot point anyways as I refactored the whole mess into something much less weird. It'll be an interesting question though to pose to a couple of the devs at work, though I'll reduce the complexity of it omitting the DataContext base class - it's rather superfluous to the example.

                          Latest Article - Building a Prototype Web-Based Diagramming Tool with SVG and Javascript 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

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

                          OK, so it's not quite as bad as I though. :) You could still break it though:

                          var context1 = new ModelDataContext(new SqlConnection("server=A;database=B"));
                          var context2 = new ModelDataContext(new SqlConnection("server=C;database=D"));

                          CreateNewContext(context1, out var newConn, out var newContext);

                          // As expected:
                          Console.WriteLine(newConn.ConnectionString == context1.Connection.ConnectionString); // True

                          // Not as expected:
                          Console.WriteLine(newContext.Connection.ConnectionString == context1.Connection.ConnectionString); // False
                          Console.WriteLine(newContext.Connection.ConnectionString == newConn.ConnectionString); // False
                          Console.WriteLine(newContext.Connection == newConn); // False

                          // Also not as expected:
                          Console.WriteLine(newContext.Connection.ConnectionString == context2.Connection.ConnectionString); // True


                          "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

                          M 1 Reply Last reply
                          0
                          • OriginalGriffO OriginalGriff

                            You probably could, with a bit of thinking about it - it's obvious when you see it, but it's a stinker to spot if you didn't write the code (and probably even harder if you did if you are anything like me: I tend to see what I meant to write, rather than what I did :-O )

                            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
                            #16

                            I also see what I meant to write as opposed to what I actually wrote. I've been tired and looked at two spellings of same word and get compiler errors and don't spot the error for some time.

                            Everyone has a photographic memory; some just don't have film. Steven Wright

                            OriginalGriffO 1 Reply Last reply
                            0
                            • Mike HankeyM Mike Hankey

                              I also see what I meant to write as opposed to what I actually wrote. I've been tired and looked at two spellings of same word and get compiler errors and don't spot the error for some time.

                              Everyone has a photographic memory; some just don't have film. Steven Wright

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

                              Annoying, isn't it? :-D

                              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

                              Mike HankeyM 1 Reply Last reply
                              0
                              • OriginalGriffO OriginalGriff

                                Annoying, isn't it? :-D

                                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
                                #18

                                Yes very frustrating. As I get older it seems to be more prevalent.

                                Everyone has a photographic memory; some just don't have film. Steven Wright

                                1 Reply Last reply
                                0
                                • Richard DeemingR Richard Deeming

                                  OK, so it's not quite as bad as I though. :) You could still break it though:

                                  var context1 = new ModelDataContext(new SqlConnection("server=A;database=B"));
                                  var context2 = new ModelDataContext(new SqlConnection("server=C;database=D"));

                                  CreateNewContext(context1, out var newConn, out var newContext);

                                  // As expected:
                                  Console.WriteLine(newConn.ConnectionString == context1.Connection.ConnectionString); // True

                                  // Not as expected:
                                  Console.WriteLine(newContext.Connection.ConnectionString == context1.Connection.ConnectionString); // False
                                  Console.WriteLine(newContext.Connection.ConnectionString == newConn.ConnectionString); // False
                                  Console.WriteLine(newContext.Connection == newConn); // False

                                  // Also not as expected:
                                  Console.WriteLine(newContext.Connection.ConnectionString == context2.Connection.ConnectionString); // True


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

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

                                  Richard Deeming wrote:

                                  You could still break it though:

                                  Yeah, but it's never used that way - two different connection strings. But ideally, it shouldn't be possible to use it that way. Sigh. The irony of this is that it's code I wrote a while back that my DataContext extension methods rely on, and looking at this now, it's some serious code smell. Fortunately, fixing it affects only a couple web servers that are in operation, but I feel embarrassed. But I blame .NET's DataContext. :laugh: It does way to much with regards to the state of the Table object. I get what they're trying to do, but there must be a better way that doesn't end up throwing exceptions like "this object was created in a different data context."

                                  Latest Article - Building a Prototype Web-Based Diagramming Tool with SVG and Javascript 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

                                  1 Reply Last reply
                                  0
                                  • M Marc Clifton

                                    And no, this isn't a programming question in the lounge. I started asking this question in the QA forum because it had me totally stumped. As I was filling out the "What I've tried" I had a major :doh: :doh: :doh: :doh: moment. To prove I'm not asking for help on the lounge, I posted a solution on [my blog](https://marcclifton.wordpress.com/2018/05/31/the-fix/). You'll need to use the password "fizbin" as the blog post is specifically for this lounge post and eventually I'll delete the post. It is a fun one though. Here's the code:

                                    public class ModelDataContext : DataContext
                                    {
                                        public static ModelDataContext Context;
                                    
                                        public ModelDataContext(DbConnection conn) : base(conn)
                                        {
                                            Context = this;
                                        }
                                    }
                                    
                                    class Program
                                    {
                                        static ModelDataContext mdc = new ModelDataContext(new SqlConnection("\[some string\]"));
                                    
                                        static void CreateNewContext(DataContext context, out SqlConnection conn, out DataContext newContext)
                                        {
                                            conn = new SqlConnection(context.Connection.ConnectionString);
                                            newContext = (DataContext)Activator.CreateInstance(context.GetType(), new object\[\] { conn });
                                            Console.WriteLine(context == newContext);
                                        }
                                    
                                        static void Main(string\[\] args)
                                        {
                                            SqlConnection conn2;
                                            DataContext newdc;
                                            CreateNewContext(ModelDataContext.Context, out conn2, out newdc);
                                    
                                            Console.WriteLine(ModelDataContext.Context == newdc);
                                        }
                                    }
                                    

                                    and the result is: False True Why is the second equality True when the first is False??? And for the bonus prize, what's a fix?

                                    Latest Article - Building a Prototype Web-Based Diagramming Tool with SVG and Javascript 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

                                    S Offline
                                    S Offline
                                    soulesurfer
                                    wrote on last edited by
                                    #20

                                    The reason for the results are pretty obvious, when a new instance is created in "CreateNewContext", the parameter "context" is still referring to the original context, not the new one ==> false; When the main program does the compare afterwards, the comparison is done to the static that holds the new context ==> true. Fixing this is not obvious because you didn't specify what the correct behavior should be. Do you wish it to be "True" always, or "False" always :) Simply update the context parameter in the method to get True always, but I would personally recommend to re-write this whole thing, it is full of code smells. Perhaps some practice in TDD would also be helpful. Cheers, Anthony

                                    1 Reply Last reply
                                    0
                                    • M Marc Clifton

                                      And no, this isn't a programming question in the lounge. I started asking this question in the QA forum because it had me totally stumped. As I was filling out the "What I've tried" I had a major :doh: :doh: :doh: :doh: moment. To prove I'm not asking for help on the lounge, I posted a solution on [my blog](https://marcclifton.wordpress.com/2018/05/31/the-fix/). You'll need to use the password "fizbin" as the blog post is specifically for this lounge post and eventually I'll delete the post. It is a fun one though. Here's the code:

                                      public class ModelDataContext : DataContext
                                      {
                                          public static ModelDataContext Context;
                                      
                                          public ModelDataContext(DbConnection conn) : base(conn)
                                          {
                                              Context = this;
                                          }
                                      }
                                      
                                      class Program
                                      {
                                          static ModelDataContext mdc = new ModelDataContext(new SqlConnection("\[some string\]"));
                                      
                                          static void CreateNewContext(DataContext context, out SqlConnection conn, out DataContext newContext)
                                          {
                                              conn = new SqlConnection(context.Connection.ConnectionString);
                                              newContext = (DataContext)Activator.CreateInstance(context.GetType(), new object\[\] { conn });
                                              Console.WriteLine(context == newContext);
                                          }
                                      
                                          static void Main(string\[\] args)
                                          {
                                              SqlConnection conn2;
                                              DataContext newdc;
                                              CreateNewContext(ModelDataContext.Context, out conn2, out newdc);
                                      
                                              Console.WriteLine(ModelDataContext.Context == newdc);
                                          }
                                      }
                                      

                                      and the result is: False True Why is the second equality True when the first is False??? And for the bonus prize, what's a fix?

                                      Latest Article - Building a Prototype Web-Based Diagramming Tool with SVG and Javascript 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

                                      E Offline
                                      E Offline
                                      englebart
                                      wrote on last edited by
                                      #21

                                      It took about a minute to solve. Assigning over the static for each constructor call is a WTF (as others have called out). Way too many statics in this Program, if it was rewritten to eliminate all of the statics, then the Program instance would hold a single context and the Main would look like this:

                                      Main(...)
                                      {
                                      new Program().Run();
                                      }

                                      If new instances of the "context" are really needed, then create a Copy constructor to reuse the default context settings on a new instance. Or use your favorite IOC container.

                                      1 Reply Last reply
                                      0
                                      • OriginalGriffO OriginalGriff

                                        You probably could, with a bit of thinking about it - it's obvious when you see it, but it's a stinker to spot if you didn't write the code (and probably even harder if you did if you are anything like me: I tend to see what I meant to write, rather than what I did :-O )

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

                                        U Offline
                                        U Offline
                                        User 11542641
                                        wrote on last edited by
                                        #22

                                        OriginalGriff wrote:

                                        I tend to see what I meant to write, rather than what I did

                                        Yup that's me! As an answer: I haven't gone further in the thread, but at first glance the FALSE comes from comparing 2 different instances, where the TRUE result is comparing the same instance to itself? Fix: the first comparison is not necessary

                                        1 Reply Last reply
                                        0
                                        • M Marc Clifton

                                          And no, this isn't a programming question in the lounge. I started asking this question in the QA forum because it had me totally stumped. As I was filling out the "What I've tried" I had a major :doh: :doh: :doh: :doh: moment. To prove I'm not asking for help on the lounge, I posted a solution on [my blog](https://marcclifton.wordpress.com/2018/05/31/the-fix/). You'll need to use the password "fizbin" as the blog post is specifically for this lounge post and eventually I'll delete the post. It is a fun one though. Here's the code:

                                          public class ModelDataContext : DataContext
                                          {
                                              public static ModelDataContext Context;
                                          
                                              public ModelDataContext(DbConnection conn) : base(conn)
                                              {
                                                  Context = this;
                                              }
                                          }
                                          
                                          class Program
                                          {
                                              static ModelDataContext mdc = new ModelDataContext(new SqlConnection("\[some string\]"));
                                          
                                              static void CreateNewContext(DataContext context, out SqlConnection conn, out DataContext newContext)
                                              {
                                                  conn = new SqlConnection(context.Connection.ConnectionString);
                                                  newContext = (DataContext)Activator.CreateInstance(context.GetType(), new object\[\] { conn });
                                                  Console.WriteLine(context == newContext);
                                              }
                                          
                                              static void Main(string\[\] args)
                                              {
                                                  SqlConnection conn2;
                                                  DataContext newdc;
                                                  CreateNewContext(ModelDataContext.Context, out conn2, out newdc);
                                          
                                                  Console.WriteLine(ModelDataContext.Context == newdc);
                                              }
                                          }
                                          

                                          and the result is: False True Why is the second equality True when the first is False??? And for the bonus prize, what's a fix?

                                          Latest Article - Building a Prototype Web-Based Diagramming Tool with SVG and Javascript 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

                                          J Offline
                                          J Offline
                                          jfren484
                                          wrote on last edited by
                                          #23

                                          It's the assignment of the static member from the instance constructor. HUGE no-no. If you want to make a singleton without using a DI framework, at least make the constructor private and have the static "Context" member be a property that will create a new object if one doesn't exist, and set it to a backing field. Something like this (might need to make Current a method instead of property if you need to pass constructor arguments, but you get the idea):

                                          public class Singleton
                                          {
                                          private Singleton _current;

                                          public Singleton Current
                                          {
                                          	get
                                          	{
                                          		if (\_current == null)
                                          		{
                                          			\_current = new Singleton();
                                          		}
                                          		
                                          		return \_current;
                                          	}
                                          }
                                          
                                          private Singleton()
                                          {
                                          }
                                          

                                          }

                                          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