Question

I am new to C# and have a difficulty with the code structure. My application has:

  1. GUI with button Show my Ethernet IP. When user clicks this button PC's IP address is displayed.

  2. Class ModbusTCPSlaveMachine. Within this class I create TCPListenter and supply it with PC's Ethernet IP address.

In both cases I get local IP address using the same method GetAllLocalIPv4. Right now I have 2 copies of this method in the code (in classes Form and ModbusTCPSlaveMachine) which is not good I guess. For example, in Python I would simply place the method in some utility module. I am aware that methods cannot be located directly in the namespace in C# while don't quite understand why.

The option I can think of is to place this function in a separate class - some utility class containing a single method (based on Python experience). Not sure if this is reasonable solution in C# beacuse this utility class looks like a meaningless container to me.

How can/should I solve the problem?

Was it helpful?

Solution

Just using a static method is the way to go here. If your function “belongs” to some existing class you can declare it as a public static method there. If it should be separate, you can put the method into a static class. A C# static class has no constructor and cannot be instantiated, and is therefore suitable as a namespace for functions.

As an example in the standard library, consider the Math class.

OTHER TIPS

Placing a method in a normal class has these benifits:

  1. You can put related methods in the same class and they can be moved around together.

  2. You can initialize object state at an earlier time then when the method is called. This gives you the same benefits a closure has.

  3. You can override the method with a different method without changing the clients that use it.

If none of that will ever mater to you then static saves you some keyboard typing.

Are you sure you don't want to put this as a normal member function in its own class, maybe called NetworkInfo? Then you could mock it in test cases and have predictable results that don't depend on the machine the code is running on.

Licensed under: CC-BY-SA with attribution
scroll top