Search code examples
c#classambiguityballoon-tip

Is it bad to create an object twice from 2 different classes?


I have a main form where when a user clicks a button it brings up a balloon tip. The balloon tip is an object instantiated within my Main form class from my BalloonTip class. I then have a second form for settings. When the user clicks something in the settings form a balloon tip occurs as well. I currently have a balloontip object instantiated in my Main class as well as my SettingsForm class. My two questions are:

  1. Is there a more appropriate way to deal with this type of situation?
  2. If creating an object twice 1 in each class, will it cause any kind of ambiguity in the compiler if the objects have the same name (i.e. objectBalloon)?

Solution

  • When you instantiate an object, this is always within a certain scope.

    So for example:

    public void DoSomething()
    {
        BalloonTip b = new BalloonTip();
    
        DoSomethingElse();
    }
    
    public void DoSomethingElse()
    {
        BalloonTip b = new BalloonTip();
    }
    

    Would give you two different instances of BalloonTip, which are both called 'b' but they are both only valid within the scope of the function in which they are declared.

    You should see a class definition as a blueprint from which multiple objects can be instantiated. In one scope you can have several instances but they should have a different name.

    When scopes don't overlap you can use the same name to point to a different instance.

    You can also pass an instance to another method and in that function you could refer to the instance by another name.

    public void DoSomething()
    {
        BalloonTip b = new BalloonTip();
    
        DoSomethingElse(b);
    }
    
    public void DoSomethingElse(BalloonTip c)
    {
      // c points to the same instance as b in the previous function
    }