3

I understand that in OOP languages like C#, it is generally viewed as bad practice to create utility classes, and it's preferable to put methods in the classes in which they will be used.

To that end, I wanted to create a transpose() extension method for double[,] types; however, it told me that extension methods must be declared in non-generic static classes. The problem is that the class that's supposed to utilize the method is meant to be instantiated.

Should I create a static Math class (I do have other methods I could put in it), or should I just make it a regular function rather than a static function?

(The class it's in is a neuralNetwork class, and it doesn't really make sense to create a static class and have neuralNetwork inherit from it).

  • 4
    eh? Extension methods are invoked from instances, even if they're declared in a static class. Could you clarify a little bit the problem you're encountering, or options you're considering? – Telastyn Mar 5 at 22:58
6

Best Practices and Good Design are things you should strive to follow, but there's always an exception or valid reason to violate them.

This is one of the necessary exceptions to "No Utility Classes". The importance of the class being a Non-Generic Static is deep in the guts of C#, this is how a class is able to find the extension methods at compile time (note: not a fully accurate explanation). If you pop open the code of Entity Framework, you can see this in action against the various types of IQueryable getting extension methods like ToList().

From a design standpoint, an Extension class is considered good design since it adheres to as many SOLID Principles as it can (Single Responsibility, Open-Closed, Interface Segregation and Dependency Inversion, if you squint a little) while still following the rules of the language (it must be Static and Non-Generic).

  • Thank you! Nice explanation ^^ – Tara Stahler Mar 6 at 0:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.