locked
static classes don't work as advertised RRS feed

  • Question

  • I am new to C#.  In C, you can have global variables.  In C#, I read that I can use a static class instead.  So I created one as follows:

     public static class Class1
        {
            static private int uc;

                public static int urlcount
                {
                    get
                    {
                        return uc;
                    }
                    set
                    {
                        uc = value;
                    }
                }
            
        }

    And I use this class as follows:
                Class1.urlcount = (int)(this.comboBox1.SelectedValue);
    The problem is that I get a message that "object reference not set to an instance of an object".
    This seems to mean I should have instantiated the class, but since its static, why bother?
    Any help is appreciated.

    Monday, May 17, 2010 12:52 PM

Answers

  • The problem here is that SelectedValue is null. Use SelectedItem instead.
    Monday, May 17, 2010 1:02 PM
  • check the RHS of the assignment, make sure (int)(this.comboBox1.SelectedValue); resolves to a valid integer. also check the value of comboBox1 and make sure it is not null.

    the following works fine:

     

    Class1.urlcount = 10;

     

    Monday, May 17, 2010 1:05 PM

All replies

  • The problem here is that SelectedValue is null. Use SelectedItem instead.
    Monday, May 17, 2010 1:02 PM
  • check the RHS of the assignment, make sure (int)(this.comboBox1.SelectedValue); resolves to a valid integer. also check the value of comboBox1 and make sure it is not null.

    the following works fine:

     

    Class1.urlcount = 10;

     

    Monday, May 17, 2010 1:05 PM