Home > Enterprise >  Best aproach to let 2 classes communicate with each other in C#
Best aproach to let 2 classes communicate with each other in C#

Time:02-16

I am relative new to OOP and C# and wanted to ask what would be the "best practice" to make two classes use Methodes from each other.

Example: I have a "Main Class", this instantiates a Class "UI" which manages the communication to a touch-display and a class "Sensor" which communicates with an external Sensor.

When someone is pushing a button on the Display, an event is triggered in the UI Class. As a reaction, the "ReadSensor" Methode form the Sensor Class needs to be called. (And the other way around, the "SensorDataCallback" needs to write stuff to the Display).

Now in C I would have made both Class Objects global, but thats no option in C#. I tried adding Methodes to the Class which accept a ref to the respective other class instance and store them, but this does not seem like the best aproach. My other way was making both classes static since there is only one Display and one Sensor, but that also can't be the best way I guess.

Sketch

Can anybody give me a hint?

CodePudding user response:

I wouldn't recommend tying two classes so closely to each other, indeed you'll end up with circular references.

Try and keep your classes self contained, so that there remains a definite separation of concerns.

Thus the Sensor class only deals with retrieving sensor data and raising notification of new values (if it is to read values automatically at regular intervals or asynchronously).

Your UI class only deals with the display and reacting to user input.

Your Main class acts as a data handler between the two.

The UI display code notifies the Main class of a user request for information; the Main class handles this and triggers the Sensor class to retrieve a new sensor value.

The Sensor class notifies/passes the new sensor value to the main class; the main class then notifies the UI that a new value is available.

Thus the Sensor does not need to know about the display, not does the display need to know about the sensor.

The above fits the current "best practice" of using MVVM (Model-View-ViewModel) structure for C# programmes with a user interface. In this case your View is the display, the ViewModel is your main class and the Model is your sensor class.

In this arrangement the View class uses databinding to retrieve the sensor value from the ViewModel. The View will raise an event (bound to a Command maybe) on the press of a button that the ViewModel reacts to, triggering it to request for updated data from the sensor. The sensor supplies that data to the ViewModel which when it updates its sensor value property raises a property changed notification that triggers the View to update.

  • Related