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 1 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

    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
        • 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

          Q Offline
          Q Offline
          Q The First Timelord
          wrote on last edited by
          #24

          The first 'true' you receive you explicitly cast the object on the function call to a DataContext type. The second you're comparing a ModelDataContext.Context object - which I'm not sure if it's a DataContext type - if not - then you're comparing unlike objects and the call will fail. Try explicitly casting the ModelDataContext.Context, and for overkill the newdc to a DataContext type and do the comparison that way. ie: Console.WriteLine((DataContext) ModelDataContext.Context == (DataContext) newdc);

          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

            A Offline
            A Offline
            AnotherKen
            wrote on last edited by
            #25

            It is a simple newb mistake. Basically, you have written overly complex code making it hard for you to debug. Simplify the syntax as much as possible and the symantec issues will reveal themselves ;)

            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