Home > Software engineering >  C# object accesible in multiple forms
C# object accesible in multiple forms

Time:07-19

I wish to create an object of a class that will be accesible in multiple forms. Basically I have a form that creates an object, but want this object accesible in whole program. Any way to do it?

CodePudding user response:

Well, there are many ways to do it.
-creating a new instance in the main form and accessing it from there
(Creating a new instance of form1 and change that forms property)
(i don't really suggest this one, but if you want you can do it)
-creating a static class with a static property (i suggest you this, it's more schematic i think)
just like this:
in MyStaticClass.cs:

public static class MyClass { public static int MyProp { get; set; }}

and accessing the property like this:

MyClass.MyProp = 1;
//or
int MyInt = MyClass.MyProp;

you could also use one of these two ways to store it:
-saving it in text format in a .txt or .bin file
-saving it in a database (something simple is sqlite but for sure it's more difficult than the others)

these are all the ideas i got

  • Related