1

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)?
Oded
  • 489,969
  • 99
  • 883
  • 1,009
Fuzz Evans
  • 2,893
  • 11
  • 44
  • 63
  • 2
    No problem with having multiple instances of a class. – David Heffernan Dec 18 '11 at 18:40
  • Why is it being created on the server side in the first place? – lucifurious Dec 18 '11 at 18:41
  • And no problem having two variables with the same name, as long as they are separated by a scope. – Patrick Dec 18 '11 at 18:41
  • It won't cause an ambiguity if the variables are not in the same scope. If there was an ambiguity, the compiler would complain anyway... – Thomas Levesque Dec 18 '11 at 18:41
  • In fact you can't have two variables with the same name in the same scope. Compiler won't let you for very obvious reasons. – David Heffernan Dec 18 '11 at 18:42
  • Slightly unrelated to the question, but good to note. This is the purpose of classes in an Object Oriented environment unless you are applying the [Singleton pattern](http://en.wikipedia.org/wiki/Singleton_pattern) to the class in question, in which case two instances would break the pattern. – Brandon Buck Dec 18 '11 at 18:51
  • Good to know. I was concerned that it would create unnecessary overhead. – Fuzz Evans Dec 18 '11 at 18:56

1 Answers1

3

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
}
Wouter de Kort
  • 39,090
  • 12
  • 84
  • 103