I have a very basic question about object-oriented programming: I have an application with several classes. So is there a way to create an object with value in its parameters and that value can be accessed by all classes in the application?
I put an example of code:
namespace Programa
{
public class Libros
{
string atrib1;
string atrib2;
string atrib3;
}
class MainWindow
{
Libros libro1 = new Libros();
libro1.atrib1 = "primer Valor";
libro1.atrib2 = "segundo Valor";
libro1.atrib3 = "tercer varlor";
}
class OtraClase
{
string variable = libro1.atrib1; //da error por problema de visibilidad de bloques
}
}
For what you're saying, I think what you're looking for is a static class so that all other classes have access to it without needing to call its constructor or anything like that.
Something like this maybe inside your namespace:
That public variable would be accessible by all other classes, and as with variables it can be done with methods.
With your example:
Although there is an answer that is fine, in reality when you have lots of classes it will not work, since you should not have a global object that encompasses everything that happens.
There is something called responsibility, and each class is responsible for its information. In the case of a global (and static) object, it works, but should not be used for your entire system.
Actually, your example is solved by passing to another class, the information it needs when it needs it.
Let's see it in code (simplified as in your example):
In this way, all objects will receive the information they need. You shouldn't have a general object that you don't know who changes it or when. In this way, the information is contained to whom it corresponds.