Color Color

Pop quiz: What does the following code do when compiled and run? class C{    public static void M(string x)    {        System.Console.WriteLine(“static M(string)”);    }    public void M(object s)    {        System.Console.WriteLine(“M(object)”);    } }class Program{    static void Main()    {        C c = new C();        c.M(“hello”);    }} (1) writes static M(string)(2) writes M(object)(3) uh, dude, this code doesn’t even…

24

Why Doesn’t C# Implement "Top Level" Methods?

C# requires that every method be in some class, even if it is a static method in a static class in the global namespace. Other languages allow “top level” functions. A recent stackoverflow post asks why that is. I am asked “why doesn’t C# implement feature X?” all the time. The answer is always the…

58

Calling static methods on type parameters is illegal, part three

There were lots of good comments on my previous entries in this series. I want to address some of them, but first I want to wrap this up by considering how a small change to the scenario makes it plausible to choose a different option.  Consider now the non-static, non-virtual instance method: public class C {…

8

Calling static methods on type parameters is illegal, part two

Last time I pointed out that static methods are always determined exactly at compile time, and used that fact to justify why static methods cannot be called on type parameter types. But aren’t the type arguments to generics actually determined at compile time? On the caller side they are, sure. But on the callee side,…

11

Calling static methods on type parameters is illegal, part one

A developer passed along a question from a customer to our internal mailing list for C# questions the other day. Consider the following: public class C { public static void M() { /*whatever*/ } }public class D : C { public new static void M() { /*whatever*/ } }public class E<T> where T : C { public…

25

Why are overloaded operators always static in C#?

A language design question was posted to the Microsoft internal C# discussion group this morning: “Why must overloaded operators be static in C#? In C++ an overloaded operator can be implemented by a static, instance or virtual method. Is there some reason for this constraint in C#?“ Before I get into the specifics, there is…

11