Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C# compiler overload resolution algorithm treat static and instance members with equal signature as equal?

Let we have two members equal by signature, but one is static and another - is not:

class Foo
{
    public void Test() { Console.WriteLine("instance"); }

    public static void Test() { Console.WriteLine("static"); }
}

but such code generate brings a compiler error:

Type 'Foo' already defines a member called 'Test' with the same parameter types

But why?

Let we compiled that successfully, then:

  • Foo.Test() should output "static"

  • new Foo().Test();should output "instance"

Can't call the static member instead of instance one because in this case another, more reasonable compiler error will occur:

Member 'Foo.Test()' cannot be accessed with an instance reference; qualify it with a type name instead

like image 546
abatishchev Avatar asked May 17 '11 15:05

abatishchev


People also ask

Why is %d used in C?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.

What does %C do in C?

%d is used to print decimal(integer) number ,while %c is used to print character . If you try to print a character with %d format the computer will print the ASCII code of the character.

Why do people still write in C?

The C programming language doesn't seem to have an expiration date. It's closeness to the hardware, great portability and deterministic usage of resources makes it ideal for low level development for such things as operating system kernels and embedded software.

Why do we use semicolon in C language?

Role of Semicolon in C: Semicolons are end statements in C. The Semicolon tells that the current statement has been terminated and other statements following are new statements. Usage of Semicolon in C will remove ambiguity and confusion while looking at the code.


1 Answers

What about, from an instance method:

Test();

What would that call? You'd probably want to give the instance method "priority" over the static method, but both would be applicable.

I would say that even if it were allowed, it would be a fundamentally bad idea to do this from a readability point of view... for example, if you changed a method which called Test from being static to instance, it would change the meaning in a subtle way.

In other words, I have no problem with this being prohibited :)

like image 180
Jon Skeet Avatar answered Sep 20 '22 19:09

Jon Skeet