Related
C# will not allow to write non-member functions and every method should be part of a class. I was thinking this as a restriction in all CLI languages. But I was wrong and I found that C++/CLI supports non-member functions. When it is compiled, compiler will make the method as member of some unnamed class.
Here is what C++/CLI standard says,
[Note: Non-member functions are treated by the CLI as members of some unnamed class; however, in C++/CLI source code, such functions cannot be qualified explicitly with that class name. end note]
The encoding of non-member functions in metadata is unspecified. [Note: This does not cause interop problems because such functions cannot have public visibility. end note]
So my question is why don't C# implement something like this? Or do you think there should not be non-member functions and every method should belong to some class?
My opinion is to have non-member function support and it helps to avoid polluting class's interface.
Any thoughts..?
See this blog posting:
http://blogs.msdn.com/ericlippert/archive/2009/06/22/why-doesn-t-c-implement-top-level-methods.aspx
(...)
I am asked "why doesn't C# implement feature X?" all the time. The answer is always the same: because no one ever designed, specified, implemented, tested, documented and shipped that feature. All six of those things are necessary to make a feature happen. All of them cost huge amounts of time, effort and money. Features are not cheap, and we try very hard to make sure that we are only shipping those features which give the best possible benefits to our users given our constrained time, effort and money budgets.
I understand that such a general answer probably does not address the specific question.
In this particular case, the clear user benefit was in the past not large enough to justify the complications to the language which would ensue. By stricting how different language entities nest inside each other we (1) restrict legal programs to be in a common, easily understood style, and (2) make it possible to define "identifier lookup" rules which are comprehensible, specifiable, implementable, testable and documentable.
By restricting method bodies to always be inside a struct or class, we make it easier to reason about the meaning of an unqualified identifier used in an invocation context; such a thing is always an invocable member of the current type (or a base type).
(...)
and this follow-up posting:
http://blogs.msdn.com/ericlippert/archive/2009/06/24/it-already-is-a-scripting-language.aspx
(...)
Like all design decisions, when we're faced with a number of competing, compelling, valuable and noncompossible ideas, we've got to find a workable compromise. We don't do that except by considering all the possibilites, which is what we're doing in this case.
(emphasis from original text)
C# doesn't allow it because Java didn't allow it.
I can think of several reasons why the designers of Java probably didn't allow it
Java was designed to be simple. They attempted to make a language without random shortcuts, so that you generally have just one simple way to do everything, even if other approaches would have been cleaner or more concise. They wanted to minimize the learning curve, and learning "a class may contain methods" is simpler than "a class may contain methods, and functions may exist outside classes".
Superficially, it looks less object-oriented. (Anything that isn't part of an object obviously can't be object-oriented? Can it? of course, C++ says yes, but C++ wasn't involved in this decision)
As I already said in comments, I think this is a good question, and there are plenty of cases where non-member functions would've been preferable. (this part is mostly a response to all the other answers saying "you don't need it")
In C++, where non-member functions are allowed, they are often preferred, for several reasons:
It aids encapsulation. The fewer methods have access to the private members of a class, the easier that class will be to refactor or maintain. Encapsulation is an important part of OOP.
Code can be reused much easier when it is not part of a class. For example, the C++ standard library defines std::find or std::sort` as non-member functions, so that they can be reused on any type of sequences, whether it is arrays, sets, linked lists or (for std::find, at least) streams. Code reuse is also an important part of OOP.
It gives us better decoupling. The find function doesn't need to know about the LinkedList class in order to be able to work on it. If it had been defined as a member function, it would be a member of the LinkedList class, basically merging the two concepts into one big blob.
Extensibility. If you accept that the interface of a class is not just "all its public members", but also "all non-member functions that operate on the class", then it becomes possible to extend the interface of a class without having to edit or even recompile the class itself.
The ability to have non-member functions may have originated with C (where you had no other choice), but in modern C++, it is a vital feature in its own right, not just for backward-comparibility purposes, but because of the simpler, cleaner and more reusable code it allows.
In fact, C# seems to have realized much the same things, much later. Why do you think extension methods were added? They are an attempt at achieving the above, while preserving the simple Java-like syntax.
Lambdas are also interesting examples, as they too are essentially small functions defined freely, not as members of any particular class. So yes, the concept of non-member functions is useful, and C#'s designers have realized the same thing. They've just tried to sneak the concept in through the back door.
http://www.ddj.com/cpp/184401197 and http://www.gotw.ca/publications/mill02.htm are two articles written by C++ experts on the subject.
Non member functions are a good thing because they improve encapsulation and reduce coupling between types. Most modern programming languages such as Haskell and F# support free functions.
What's the benefit of not putting each method in a named class? Why would a non-member function "pollute" the class's interface? If you don't want it as part of the public API of a class, either don't make it public or don't put it in that class. You can always create a different class.
I can't remember ever wanting to write a method floating around with no appropriate scope - other than anonymous functions, of course (which aren't really the same).
In short, I can't see any benefit in non-member functions, but I can see benefits in terms of consistency, naming and documentation in putting all methods in an appropriately named class.
The CLS (common language specification) says that you shouldn't have non-member functions in a library that conforms to the CLS. It's like an extra set of restrictions in addition to the basic restrictions of the CLI (common language interface).
It is possible that a future version of C# will add the ability to write a using directive that allows the static members of a class to be accessed without the class name qualification:
using System.Linq.Enumerable; // Enumerable is a static class
...
IEnumerable<int> range = Range(1, 10); // finds Enumerable.Range
Then there will be no need to change the CLS and existing libraries.
These blog posts demonstrate a library for functional programming in C#, and they use a class name that is just one letter long, to try and cut down the noise caused by the requirement to qualify static method calls. Examples like that would be made a little nicer if using directives could target classes.
Since Java, most programmers have easily accepted that any method is a member of a class. I doesn't make any considerable obstacles and make the concept of method more narrow, which make a language easier.
However, indeed, class infers object, and object infers state, so the concept of class containing only static methods looks a little absurd.
Having all code lie within classes allows for a more powerful set of reflection capabilities.
It allows the use of static intializers, which can initialize the data needed by static methods within a class.
It avoids name clashes between methods by explicitly enclosing them within a unit that cannot be added to by another compilation unit.
I think you really need to clarify what you would want to create non-member static methods to achieve.
For instance, some of the things you might want them for could be handled with Extension Methods
Another typical use (of a class which only contains static methods) is in a library. In this case, there is little harm in creating a class in an assembly which is entirely composed of static methods. It keeps them together, avoids naming collisions. After all, there are static methods in Math which serve the same purpose.
Also, you should not necessarily compare C++'s object model with C#. C++ is largely (but not perfectly) compatible with C, which didn't have a class system at all - so C++ had to support this programming idiom out of the C legacy, not for any particular design imperative.
Csharp does not have non-member function because it has copied or inspired by java's philosophy that only OOPs is the solution for all the problems and it will only allow things to be solved using OO way.
Non-member functions are very important feature if we really want to do generic programming. They are more reusable compared to putting them in a class.
CSharp has to come up with ExtensionMethods due to absence of non-member functions.
As now programming languages are moving towards functional programming paradigm and it seems to be the better way to approach and solve the problem and is the future. CSharp should rethink about it.
Bear something in mind: C++ is a much more complicated language than C#. And although they may be similiar syntactically, they are very different beasts semantically. You wouldn't think it would be terribly difficult to make a change like this, but I could see how it could be. ANTLR has a good wiki page called What makes a language problem hard? that's good to consult for questions like this. In this case:
Context sensitive lexer? You can't decide what vocabulay symbol to match unless you know what kind of sentence you are parsing.
Now instead of just worrying about functions defined in classes, we have to worry about functions defined outside classes. Conceptually, there isn't much difference. But in terms of lexing and parsing the code, now you have the added problem of having to say "if a function is outside a class, it belongs to this unnamed class. However, if it is inside the class, then it belongs to that class."
Also, if the compiler comes across a method like this:
public void Foo()
{
Bar();
}
...it now has to answer the question "is Bar located within this class or is it a global class?"
Forward or external references? I.e., multiple passes needed? Pascal has a "forward" reference to handle intra-file procedure references, but references to procedures in other files via the USES clauses etc... require special handling.
This is another thing that causes problems. Remember that C# doesn't require forward declarations. The compiler will make one pass just to determine what classes are named and what functions those classes contain. Now you have to worry about finding classes and functions where functions can be either inside or outside of a class. This is something a C++ parser doesn't have to worry about as it parses everything in order.
Now don't get me wrong, it could probably be done in C#, and I would probably use such a feature. But is it really worth all the trouble of overcoming these obstacles when you could just type a class name in front of a static method?
Free functions are very useful if you combine them with duck typing. The whole C++ STL is based on it. Hence I am sure that C# will introduce free functions when they manage to add true generics.
Like economics, language design is also about psychology. If you create appetite for true generics via free functions in C# and not deliver, then you would kill C#. Then all C# developers would move to C++ and nobody wants that to happen, not the C# community and most certainly not those invested in C++.
While it's true you need a class (e.g. a static class called FreeFunctions) to hold such functions, you're free to place using static FreeFunctions; at the top of any file that needs the functions from it, without having to litter your code with FreeFunctions. qualifiers.
I'm not sure if there's actually a case where this is demonstrably inferior to not requiring the function definitions to be contained in a class.
Look, other programming languages have a hard time to define the internal nature of a function instance from the compiler's point of view. In Pascal and C, the instances are basically defined as something that can be processed as pointer only. Especially, since reading/writing to executable code positions is what 7 out of 9 computer science professors are dead set against. As member of a class, no one does need to care how to treat its manifestation because this manifestation's type is derived from a class property. It is possible to create something that is exactly processed like a global function: a lambda function, assigned to a variable:
Func<int,int> myFunc = delegate(int var1)
{
Console.WriteLine("{0}",var1*2);
return var1*3;
};
. And it can simply be called like a global function by its variable name.
If so, the difference would be implementing a new object type on the lowest level with same behavior as another one. That is considered bad practice by experienced programmers, and was perhaps scrapped because of this.
Why are extension methods only allowed in non-nested, non-generic static class?
Is it useless to consider extension methods in nested, generic static class?
Why are extension methods only allowed in non-nested, non-generic static class?
As Pratik points out, the question we face is not "why are extension methods not allowed in nested or generic classes?" The question we face as language designers is "why should extension methods be allowed in nested or generic classes?"
Unless the feature is justified by some real-world user need, we're not going to take on the considerable costs of designing, implementing, testing, documenting and maintaining the feature.
Basically, extension methods were designed to make LINQ work. Anything that didn't contribute to making LINQ work was cut. LINQ only needs extension methods in static, non-generic, non-nested classes to work, so that's what we designed and implemented.
If you have a scenario where extension methods would be useful in non-static, generic, or nested classes then I'm happy to take a look at the scenario. The more real-world scenarios we get, the more likely it is that we'll make a feature in some hypothetical future language that benefits those scenarios.
Is it useless to consider extension methods in nested, generic static class?
No, it is a great idea to consider it. We would be remiss in our duties if we did not consider it. We considered it carefully for a long time and decided that on the basis of that consideration, the costs of doing the feature were not justified by the benefits accrued.
As Eric Lippert has written many times in his blog, each change to C# is carefully evaluated against a set of criteria to justify it and not based on technology sake alone. In this case, what was not required to enable LINQ was cut off to reduce risk. Check this blog post from Eric for a similar question.
I believe that this was done so that compiler can locate/search the extension method in reasonable amount of time. Further, note that complier search extension methods only in set of namespaces that are in file scope - this is also done for similar reasons.
If you think about generic static class scenario, compiler must try to instantiate the concrete types for all possible type combinations in order to match the extension method. Even if complier can be smart in doing this, instantiating concrete type for calling extension methods may have side effect that developer may not be aware of.
We are debating at work the best way to define methods for an entity class - as extensions methods or using partial classes. The kind of methods we're talking about don't modify the state of the entity, they are purely "helper" methods that interrogate the state and return a value.
The main benefit to both approaches is to keep the entity class clean, while still providing intellisense support to client code.
I don't have a strong preference either way but am curious to know if others have a preference (or know of documented guidelines) towards one or the other.
I started writing the list of merits for each approach that I could think of, but in the end all I've come up with is:
Partial Classes
The method definition resides within the class (even if it's another file) so Visual Studio tool support for "find method" (e.g. ALT-\ in resharper) will locate the method
The existence of the other file containing helper methods is obvious as soon as the entity class is opened due to use of the partial keyword
Extension Methods
The naming of the file ("entityNameExtension") and its whereabouts in the project (in an "Extensions" sub-folder) are intuitive and easy to search for
Can anyone else add their opinion to this?
PS I don't feel this is a duplicate of the following question, as the asker of that question was content to mark a response which outlined the functional differences as the correct answer, which doesn't answer the question about which approach is best practice in this scenario:
Partial Class vs Extension Method
EDIT - I'm seeking people's preference towards one approach or the other, as there are no documented guidelines that we can find for this particular scenario. Both approaches are possible and neither violates any design principles, so it is a matter of preference and I'd like to know yours.
In my opinion, extension methods are good for two things. First, when you apply them to interfaces, it gives you the illusion of writing an abstract base class that lets you define some common methods, but it's more flexible because a class can only have one base class but can implement multiple interfaces. Second, if you apply it to regular classes, then I tend to look at it as some kind of hacking. When the original class lacks some methods, and you really feel like they should have those methods, but they don't, and they are out of your reach, so you are forced to implement them somewhere else, as utility methods, and it gives you an illusion that it's actually there.
Both cases are syntactic sugar only in the end, but extending interfaces makes much more sense to me, if I just look at LINQ's Enumerable class for example. I've used those extension methods on dozens of completely different classes, so it really paid off. An example of a class extension method is when I made my own string.IsNullOrWhitespace before it was added to the framework.
Extending an interface seems right because the interface defines a contract, and you can rely on that contract in your extension method, but when you extend a regular class, it may change and break your extension method. Of course, interfaces may change, too, but they tend to be more thoroughly designed I think, but I don't have any statistics.
Then there's the case of object-oriented programming. Where do you feel like your method should go, who uses those additional methods, where are the boundaries. If you think a method belongs inside a class, then put it in the class. It makes sense, it's simple. People wrote really good classes before extension methods were invented, they put everything where it belonged and life was good, haha.
Partial classes are cool because they are not that big of a hack as extension methods. They are not syntactic sugar, not magic. It is merely the best and easiest way to deal with auto-generated classes, so I don't think too much of it. I've written some code generators, and they emit regions where humans can write their own stuff and it is not overwritten in subsequent code generations. It is more comfortable that way, but that's all. I can't change how .NET tools generate code, and they don't do it this way, so partial classes are the next best thing.
To sum it up, my opinion is to only use extension methods when you really have to, and go with partial classes whenever possible.
I dont know why you would create a partial class uless your original class has grown out of its purpose. Take a look at your classes you would like to extend, are they really doing one thing, or are they doing many things. Take a look at at the Single Responsibility Principle (http://en.wikipedia.org/wiki/Single_responsibility_principle).
If you can create methods that OTHER CLASSES can take advantage of, I would recommend creating an extension class. It will extend the capability of other classes, making your toolbox more flexible.
I would like to know if C# extension method is based on any existing design pattern.
A design pattern is simply a well known paradigm, i.e. "when you want to achieve X, do Y". A well known paradigm in object-oriented languages such as C# is "when you want to act on the state of an object, call a method on an instance of it".
However, before extension methods were created, you could not call your own method on an instance of an object that you could not add an implementation to (e.g. interfaces because they cannot have implementations, or library classes because they are already compiled). Extension methods fill this gap by allowing you to make methods that appear to be callable on instances of objects, while being defined externally to the implementation of the object.
So yes, arguably extension methods are based on this very simple design pattern, of making methods that act on the state of an object appear to be callable from an instance of it.
The extension methods can be thought as a replacement of the Visitor Pattern. It is also proposed that they can be used as Adapters.
In general languages evolve to make the need of design patterns less necessary. There is a quote for example that Lisp doesn't need design patterns, because everything is built in the language. So the right question will be, what design patterns do extension methods replace?
No. It's just a language feature.
They are not based on an existing design pattern. When this 'feature' was first introduced in Delphi, under the name 'class helpers', Borland even warned users away from them. They were considered a bit of a hack, but now the dust has settled they have found a place of their own.
Like everything else, use when appropriate.
The closest canonical design patterns is probably the Decorator pattern.
No, they are not, because they are only syntactic sugar.
No, but extension methods are excellent for implementing certain GoF design patterns (e.g., Prototype).
Of course you can use C# extension methods if you want to implement certain design patterns. For example simulate mixins in C#.
I wouldn't label Extension Methods as any of the common design patterns, but it can be used to implement patterns like, Decorator and Adapter etc..
The best matching design pattern to extension method is Facade pattern.
My Reason: We usually use extension methods not to introduce a new functionality beyond the target class responsibility, but simplifying using existing target class usage.
Because simplifying the target class usage is the Facade pattern concern, extension methods can alternatively be implemented using the Facade pattern.
There are some problems in extending and unit testing extension methods. So I think implementing Facade pattern is a better approach against using extension methods.
However it is possible to implement some extension methods that wrap the facade interface in order to provide a coding facility for client codes.
C# will not allow to write non-member functions and every method should be part of a class. I was thinking this as a restriction in all CLI languages. But I was wrong and I found that C++/CLI supports non-member functions. When it is compiled, compiler will make the method as member of some unnamed class.
Here is what C++/CLI standard says,
[Note: Non-member functions are treated by the CLI as members of some unnamed class; however, in C++/CLI source code, such functions cannot be qualified explicitly with that class name. end note]
The encoding of non-member functions in metadata is unspecified. [Note: This does not cause interop problems because such functions cannot have public visibility. end note]
So my question is why don't C# implement something like this? Or do you think there should not be non-member functions and every method should belong to some class?
My opinion is to have non-member function support and it helps to avoid polluting class's interface.
Any thoughts..?
See this blog posting:
http://blogs.msdn.com/ericlippert/archive/2009/06/22/why-doesn-t-c-implement-top-level-methods.aspx
(...)
I am asked "why doesn't C# implement feature X?" all the time. The answer is always the same: because no one ever designed, specified, implemented, tested, documented and shipped that feature. All six of those things are necessary to make a feature happen. All of them cost huge amounts of time, effort and money. Features are not cheap, and we try very hard to make sure that we are only shipping those features which give the best possible benefits to our users given our constrained time, effort and money budgets.
I understand that such a general answer probably does not address the specific question.
In this particular case, the clear user benefit was in the past not large enough to justify the complications to the language which would ensue. By stricting how different language entities nest inside each other we (1) restrict legal programs to be in a common, easily understood style, and (2) make it possible to define "identifier lookup" rules which are comprehensible, specifiable, implementable, testable and documentable.
By restricting method bodies to always be inside a struct or class, we make it easier to reason about the meaning of an unqualified identifier used in an invocation context; such a thing is always an invocable member of the current type (or a base type).
(...)
and this follow-up posting:
http://blogs.msdn.com/ericlippert/archive/2009/06/24/it-already-is-a-scripting-language.aspx
(...)
Like all design decisions, when we're faced with a number of competing, compelling, valuable and noncompossible ideas, we've got to find a workable compromise. We don't do that except by considering all the possibilites, which is what we're doing in this case.
(emphasis from original text)
C# doesn't allow it because Java didn't allow it.
I can think of several reasons why the designers of Java probably didn't allow it
Java was designed to be simple. They attempted to make a language without random shortcuts, so that you generally have just one simple way to do everything, even if other approaches would have been cleaner or more concise. They wanted to minimize the learning curve, and learning "a class may contain methods" is simpler than "a class may contain methods, and functions may exist outside classes".
Superficially, it looks less object-oriented. (Anything that isn't part of an object obviously can't be object-oriented? Can it? of course, C++ says yes, but C++ wasn't involved in this decision)
As I already said in comments, I think this is a good question, and there are plenty of cases where non-member functions would've been preferable. (this part is mostly a response to all the other answers saying "you don't need it")
In C++, where non-member functions are allowed, they are often preferred, for several reasons:
It aids encapsulation. The fewer methods have access to the private members of a class, the easier that class will be to refactor or maintain. Encapsulation is an important part of OOP.
Code can be reused much easier when it is not part of a class. For example, the C++ standard library defines std::find or std::sort` as non-member functions, so that they can be reused on any type of sequences, whether it is arrays, sets, linked lists or (for std::find, at least) streams. Code reuse is also an important part of OOP.
It gives us better decoupling. The find function doesn't need to know about the LinkedList class in order to be able to work on it. If it had been defined as a member function, it would be a member of the LinkedList class, basically merging the two concepts into one big blob.
Extensibility. If you accept that the interface of a class is not just "all its public members", but also "all non-member functions that operate on the class", then it becomes possible to extend the interface of a class without having to edit or even recompile the class itself.
The ability to have non-member functions may have originated with C (where you had no other choice), but in modern C++, it is a vital feature in its own right, not just for backward-comparibility purposes, but because of the simpler, cleaner and more reusable code it allows.
In fact, C# seems to have realized much the same things, much later. Why do you think extension methods were added? They are an attempt at achieving the above, while preserving the simple Java-like syntax.
Lambdas are also interesting examples, as they too are essentially small functions defined freely, not as members of any particular class. So yes, the concept of non-member functions is useful, and C#'s designers have realized the same thing. They've just tried to sneak the concept in through the back door.
http://www.ddj.com/cpp/184401197 and http://www.gotw.ca/publications/mill02.htm are two articles written by C++ experts on the subject.
Non member functions are a good thing because they improve encapsulation and reduce coupling between types. Most modern programming languages such as Haskell and F# support free functions.
What's the benefit of not putting each method in a named class? Why would a non-member function "pollute" the class's interface? If you don't want it as part of the public API of a class, either don't make it public or don't put it in that class. You can always create a different class.
I can't remember ever wanting to write a method floating around with no appropriate scope - other than anonymous functions, of course (which aren't really the same).
In short, I can't see any benefit in non-member functions, but I can see benefits in terms of consistency, naming and documentation in putting all methods in an appropriately named class.
The CLS (common language specification) says that you shouldn't have non-member functions in a library that conforms to the CLS. It's like an extra set of restrictions in addition to the basic restrictions of the CLI (common language interface).
It is possible that a future version of C# will add the ability to write a using directive that allows the static members of a class to be accessed without the class name qualification:
using System.Linq.Enumerable; // Enumerable is a static class
...
IEnumerable<int> range = Range(1, 10); // finds Enumerable.Range
Then there will be no need to change the CLS and existing libraries.
These blog posts demonstrate a library for functional programming in C#, and they use a class name that is just one letter long, to try and cut down the noise caused by the requirement to qualify static method calls. Examples like that would be made a little nicer if using directives could target classes.
Since Java, most programmers have easily accepted that any method is a member of a class. I doesn't make any considerable obstacles and make the concept of method more narrow, which make a language easier.
However, indeed, class infers object, and object infers state, so the concept of class containing only static methods looks a little absurd.
Having all code lie within classes allows for a more powerful set of reflection capabilities.
It allows the use of static intializers, which can initialize the data needed by static methods within a class.
It avoids name clashes between methods by explicitly enclosing them within a unit that cannot be added to by another compilation unit.
I think you really need to clarify what you would want to create non-member static methods to achieve.
For instance, some of the things you might want them for could be handled with Extension Methods
Another typical use (of a class which only contains static methods) is in a library. In this case, there is little harm in creating a class in an assembly which is entirely composed of static methods. It keeps them together, avoids naming collisions. After all, there are static methods in Math which serve the same purpose.
Also, you should not necessarily compare C++'s object model with C#. C++ is largely (but not perfectly) compatible with C, which didn't have a class system at all - so C++ had to support this programming idiom out of the C legacy, not for any particular design imperative.
Csharp does not have non-member function because it has copied or inspired by java's philosophy that only OOPs is the solution for all the problems and it will only allow things to be solved using OO way.
Non-member functions are very important feature if we really want to do generic programming. They are more reusable compared to putting them in a class.
CSharp has to come up with ExtensionMethods due to absence of non-member functions.
As now programming languages are moving towards functional programming paradigm and it seems to be the better way to approach and solve the problem and is the future. CSharp should rethink about it.
Bear something in mind: C++ is a much more complicated language than C#. And although they may be similiar syntactically, they are very different beasts semantically. You wouldn't think it would be terribly difficult to make a change like this, but I could see how it could be. ANTLR has a good wiki page called What makes a language problem hard? that's good to consult for questions like this. In this case:
Context sensitive lexer? You can't decide what vocabulay symbol to match unless you know what kind of sentence you are parsing.
Now instead of just worrying about functions defined in classes, we have to worry about functions defined outside classes. Conceptually, there isn't much difference. But in terms of lexing and parsing the code, now you have the added problem of having to say "if a function is outside a class, it belongs to this unnamed class. However, if it is inside the class, then it belongs to that class."
Also, if the compiler comes across a method like this:
public void Foo()
{
Bar();
}
...it now has to answer the question "is Bar located within this class or is it a global class?"
Forward or external references? I.e., multiple passes needed? Pascal has a "forward" reference to handle intra-file procedure references, but references to procedures in other files via the USES clauses etc... require special handling.
This is another thing that causes problems. Remember that C# doesn't require forward declarations. The compiler will make one pass just to determine what classes are named and what functions those classes contain. Now you have to worry about finding classes and functions where functions can be either inside or outside of a class. This is something a C++ parser doesn't have to worry about as it parses everything in order.
Now don't get me wrong, it could probably be done in C#, and I would probably use such a feature. But is it really worth all the trouble of overcoming these obstacles when you could just type a class name in front of a static method?
Free functions are very useful if you combine them with duck typing. The whole C++ STL is based on it. Hence I am sure that C# will introduce free functions when they manage to add true generics.
Like economics, language design is also about psychology. If you create appetite for true generics via free functions in C# and not deliver, then you would kill C#. Then all C# developers would move to C++ and nobody wants that to happen, not the C# community and most certainly not those invested in C++.
While it's true you need a class (e.g. a static class called FreeFunctions) to hold such functions, you're free to place using static FreeFunctions; at the top of any file that needs the functions from it, without having to litter your code with FreeFunctions. qualifiers.
I'm not sure if there's actually a case where this is demonstrably inferior to not requiring the function definitions to be contained in a class.
Look, other programming languages have a hard time to define the internal nature of a function instance from the compiler's point of view. In Pascal and C, the instances are basically defined as something that can be processed as pointer only. Especially, since reading/writing to executable code positions is what 7 out of 9 computer science professors are dead set against. As member of a class, no one does need to care how to treat its manifestation because this manifestation's type is derived from a class property. It is possible to create something that is exactly processed like a global function: a lambda function, assigned to a variable:
Func<int,int> myFunc = delegate(int var1)
{
Console.WriteLine("{0}",var1*2);
return var1*3;
};
. And it can simply be called like a global function by its variable name.
If so, the difference would be implementing a new object type on the lowest level with same behavior as another one. That is considered bad practice by experienced programmers, and was perhaps scrapped because of this.