Reputation: 85
I have a class with public methods defined like this:
public class Core1 {
//...
//...
public void DoSmth()
{
//....
}
//.....
//....
}
public partial class Form1 : Form
{
//.....
And I want to initialize the class in Form1, let say:
Core1 newcore = new Core1();
And then access some of the public methods of newcore (DmSmth() for ex.), in some other forms, let say Form3 or Form4. What is the best way to do this?
Thanks.
Upvotes: 0
Views: 4477
Reputation: 3960
If you are sharing only one instance of this object Core1, then you could do this
// in Form1
static Core1 newcore = new Core1();
public static Core1 CoreObject
{
get { return newcore; }
}
In other forms you could do things like the following to get the object
Core1 object = Form1.CoreObject;
// or...
Form1.CoreObject.SomeMethod();
I wouldn't recommend you do public var, a property would give you better control and flexibility
Upvotes: 0
Reputation: 203814
If it makes sense for there to only ever be a single instance of Core1, either because it doesn't have any state (only methods that act solely on parameters; this would be called a utility class) then it can be static, along with it's method(s) so that it never needs to exist. If it is possibly going to be one of multiple instances of the class then you shouldn't be using static anywhere. You should create one in one of the forms (wherever it makes sense) and then pass that value around to the other forms. This could be either through public properties, through constructors, etc.
Upvotes: 1
Reputation: 880
Create a static public variable of new core ex:
public partial class Form1 : Form
{
public static Core1 newcore = new Core1();
}
and in form 2:
public partial class Form2 : Form
{
public void Test()
{
Namespace.Form1.newcore.DoSmth();
}
}
Or you can make Core1 a static class:
public static class Core1
{
public static void DoSmth()
{
}
}
If that helps
Upvotes: 0
Reputation: 25732
Basically use a public static instance:
public static readonly Core1 Newcore = new Core1();
and access it like this in any form (note that this is not thread safe):
var result = Form1.Core1.DmSmth();
Upvotes: 2
Reputation: 460058
You could provide a public property in Form1
to provide access to the whole object or some of it's properties/methods.
private Core1 newcore = new Core1();
public Core1 Core
{
get { return newcore; }
set { newcore = value; }
}
public void DoSmthWithCore()
{
newcore.DoSmth();
}
If another form needs access, it needs a reference to Form1
. For example by passing an instance to the constructor of Form2
or any methods there or by using Application.OpenForms
.
In general it's better to provide minimum access to outer classes.
Upvotes: 0