Best way to exchange data between classes in C #
I am trying to write a windows form application. I have multiple buttons and I need to change the image of the buttons according to the state of the variable. I put images in the Resources folder and Im trying to find them like this:
Image im = Properties .Resources.green;
How can I achieve this im value from all classes in my project just by using the variable name "im"?
What you are looking for is a simple global variable, but they are missing in C #. A simple alternative would be to create a class named MyImages (or whatever) and then make "im" a static public field, like this:
public class MyImages
{
public static Image im = Properties.Resources.green;
}
Then, from anywhere in your project, you can access "im" with code like this:
Image newImage = MyImages.im;
Some programmers may be horrified by something like this and insist on "dependency injection" or the correct singleton, or make "im" private and create a get / set property public, or something like that. However, if you literally need to access this image from anywhere in your code, this is an easy and efficient way to do it, and it accomplishes the task of keeping the code to generate the image in one place.
source to share