Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freestanding functions in C# [closed]

Tags:

c#

Being a C++ programmer, every time I work with C# I wonder why it lacks support for freestanding functions; in other words: functions that are not part of any class. I really miss this feature, because standalone functions allow to add functionality to classes without requiring full private access, avoiding hard-to-maintain monolith classes. Furthermore, it allows extending third party libraries. I know you can use a static class, but the class name is totally irrelevant, making the client code unnecessarily verbose.

For example. I want to create a helper function to count the words in a string. How can I avoid having to write "StringHelperClass.CountWords();" in the client code? StringHelperClass acts as a namespace, only I cannot write "using StringHelperClass;". I am forced to repeat "StringHelperClass" with every usage, whereas it is obvious that it is a string helper function, as its only parameter is a string.

Is there a way to extend a class' functionality, while keeping the client code concise?

like image 237
Dimitri C. Avatar asked May 18 '09 10:05

Dimitri C.


1 Answers

Edit: note that since the using static .... directive was added in C# 6, this can largely be considered an equivalent feature. Just use regular .NET static methods, then use a using static directive, and those methods are immediately available to you.


The better question would be:

"Why should it include it?"

Given that C# holds together pretty well without freestanding functions, what is the requirement to add them? In particular, static utility classes work fine for hosting such (either as regular or extension methods), and allow simple disambiguation when conflicts arise.

It also (as OregonGhost notes in the comments) helps modularize the code, preventing death-by-IntelliSense etc.

So: why add them? What is the problem (in C#) that isn't already solved?

like image 197
Marc Gravell Avatar answered Oct 10 '22 03:10

Marc Gravell