Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# classes - Why so many static methods?

Tags:

I'm pretty new to C# so bear with me.

One of the first things I noticed about C# is that many of the classes are static method heavy. For example...

Why is it:

Array.ForEach(arr, proc)

instead of:

arr.ForEach(proc)

And why is it:

Array.Sort(arr)

instead of:

arr.Sort()

Feel free to point me to some FAQ on the net. If a detailed answer is in some book somewhere, I'd welcome a pointer to that as well. I'm looking for the definitive answer on this, but your speculation is welcome.

like image 481
dharmatech Avatar asked Oct 24 '11 01:10

dharmatech


2 Answers

Because those are utility classes. The class construction is just a way to group them together, considering there are no free functions in C#.

like image 119
K-ballo Avatar answered Sep 21 '22 13:09

K-ballo


Assuming this answer is correct, instance methods require additional space in a "method table." Making array methods static may have been an early space-saving decision.

This, along with avoiding the this pointer check that Amitd references, could provide significant performance gains for something as ubiquitous as arrays.

like image 30
Daniel Avatar answered Sep 21 '22 13:09

Daniel