none
Instantiating an existing class RRS feed

  • Question

  • Hi Guys,

    I'm new to coding in vb.net and I have run into a problem where i have "myclass" in my project.  I have created some properties within this class that i have set.

    I have two user controls...

    usercontrol1

    usercontrol2

    In "usercontrol1" i set the properties inside "myclass" and in "usercontrol2" I am trying to call the properties but they have null values now.

    I am to the assumption that because inside "usercontrol1" I instantiated a new "myclass" and set the properties, then when I am inside "usercontrol2" and also instantiate a new "myclass" that it is resetting those properties.  I'm not sure if my assumption is correct or not but thus you have my problem.  Any help on resolving this issue would be great.  I appreciate any and all help.

    Sidequestion - if my assumption is correct and by instantiating a new "myclass" in "usercontrol2" is in fact resetting the properties how or what is the best way to maintain a set of properties that can maintain when i switch user controls.


    Thanks.

    Friday, December 31, 2010 12:48 AM

Answers

  • Hi,

    when you create 2 instances of a class, them each instance will have their own properties. Setting properties on one instance will not change / override the value of the other instance.

    The only exception are so called static elements (In VB.Net the keyword for this is shared!). This means, that the value belongs to the class itself and not to the instance so it only exists one time. (And you should use MyClass.MyProperty instead of myInstanceOfMyClass.MyProperty)

    And if you want to share the instance, you could create the instance in the form where both controls are in and the form then simply gives the instance to the controls. (E.g. through a Property of the user controls).

    (Or you can build up a Property that checks if an instance is already there and if not, it creates a new instance. And then inside the form you could do something like control1.MyClassInstance = control2.MyClassInstance which seems to be more logic in my eyes as long as MyClass is not implementing IDisposal where you want to have exactly one instance, which is responsible.)

    Hope I didn't confuse you and my post helped a little.

    With kind regards,

    Konrad

    • Marked as answer by Cookie Luo Thursday, January 6, 2011 1:39 AM
    Friday, December 31, 2010 7:08 AM