Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is dotnet's char.IsLower() a static method?

Tags:

.net

char

static

This seems to go against every design guideline. A static method that accepts a single argument of type T should usually just be a member method.

It's so bizzare I actually had to post a StackOverflow question to understand IsUpper exists (as it didn't show up in auto-completion)

Edit

I understand my earlier statement needs a little explaining. An example of a good design is String.ToLower(). Instead of it being prototyped as static void ToLower(String foo), it is a member method. It's pretty obvious (to me at least) that the same should hold for char.IsLower().

like image 277
ripper234 Avatar asked Dec 23 '08 16:12

ripper234


3 Answers

Instance methods on structures are not thread safe. Static methods on the other hand are.

Static methods receive a copy of the structure, instance methods a managed pointer. Accessing data through a pointer is not a tread safe operation and can easily lead to race conditions.

That's why most methods on structures/primitives are static and not instance.

Se here a similar question.

Why IsNan is a static method on the Double class instead of an instance property ?

like image 174
Pop Catalin Avatar answered Nov 06 '22 01:11

Pop Catalin


See also this question.

The short version - The initial IDE had trouble coming up with intellisense when invoked from a string literal (and I'm assuming char literals too). So the designers made the methods static to get around this problem.

REEDIT: I had a little rant here about the .NET designers bowing to pressure from IDE designers. But having seen Pop's answer to this question I'm less sure about this now.

EDIT2: Tim in the comments asked if we knew this to be true, or is it just a guess. I couldn't find an exact reference to this issue but I found an article from 2002 talking about an intellisense bug in a string literal. It's about halfway down this page.

like image 27
Cameron MacFarland Avatar answered Nov 06 '22 01:11

Cameron MacFarland


In my point of view, it does make sense.

There are many static methods which accept single argument. It would not be so nice to calculate a square root using something like this:

double d = 100.0;
Console.WriteLine("Square root of d is " + d.Sqrt());

This would decrease "Cohesion" in term of OO design which is not a good practice. It will be more nice to separate this responsibility to the Math class.

double d = 100.0;
Console.WriteLine("Square root of d is " + Math.Sqrt(d));
like image 28
Gant Avatar answered Nov 06 '22 03:11

Gant