Access to instance objects in different classes

  • Thread starter Thread starter MikeAth via DotNetMonster.com
  • Start date Start date
M

MikeAth via DotNetMonster.com

Hi all,
I have two different classes and one instance of the Form.
I would like to access the members of the Form instance in both classes
without having to create a new instance in the other class, because that
would give me access to different members than in the first instance and
would not behave as one global object. How can I do that, any guess?


Thanks.
 
Mike,

By passing the referenes for reference types and the value for value types
(which is the standard passing way)

I hope this helps,

Cor
 
I have two different classes and one instance of the Form.
I would like to access the members of the Form instance in both classes
without having to create a new instance in the other class, because that
would give me access to different members than in the first instance and
would not behave as one global object. How can I do that, any guess?

You need the Singleton design pattern.

public class MyClass
{
private static MyClass instance = null;

private MyClass() {}

public static MyClass Instance()
{
if (instance == null)
instance = new MyClass();
return instance;
}
}

Called from either form like this :

{
MyClass formUser = MyClass.Instance();
...
}

Joanna
 
Thanks, I think that singleton design pattern is exactly what I need. I
just expected such access to be more common and easily usable in C#, but I
hope it will work fine this way.
 
Joanna Carter (TeamB) said:
You need the Singleton design pattern.

That sounds like a bad idea to me in this case. As Cor said, all the OP
needs is for the reference to the form to be given to both of the other
classes in some way or other, whether it's by calling a method, setting
a property, or passing a reference in the constructor. There's no need
for a singleton.
public class MyClass
{
private static MyClass instance = null;

private MyClass() {}

public static MyClass Instance()
{
if (instance == null)
instance = new MyClass();
return instance;
}
}

That's not a thread-safe way of implementing a singleton. See
http://www.pobox.com/~skeet/csharp/singleton.html
 
Back
Top