Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which C# method overload is chosen?

Tags:

c#

.net

generics

Why is the generic method called when both overloads would match?

public static void method1(object obj) {     Console.WriteLine("Object"); }  public static void method1<T>(T t) {     Console.WriteLine("Type T"); }  public static void Main(String args[]) {     method1("xyz"); //Will print "Type T"; } 

There should not be any conflicts here, right?

like image 709
Parashuram Avatar asked Oct 01 '15 16:10

Parashuram


People also ask

What is || in C programming?

Logical OR operator: || The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool .

Is C still used?

C exists everywhere in the modern world. A lot of applications, including Microsoft Windows, run on C. Even Python, one of the most popular languages, was built on C. Modern applications add new features implemented using high-level languages, but a lot of their existing functionalities use C.

Which language C is?

C (/ˈsiː/, as in the letter c) is a general-purpose computer programming language. It was created in the 1970s by Dennis Ritchie, and remains very widely used and influential.

Which C program is best?

NetBeans, developed by Apache Software Foundation – Oracle Corporation, is also one of the most widely used IDE by the C/C++ developers. This free and open-source Integrated Development Environment allows you to create C and C++ applications with dynamic and static libraries.


1 Answers

Overloads are resolved by choosing the most specific overload. In this case, method1<string>(string) is more specific than method1(object) so that is the overload chosen.

There are details in section 7.4.2 of the C# specification.

If you want to select a specific overload, you can do so by explicitly casting the parameters to the types that you want. The following will call the method1(object) overload instead of the generic one:

method1((object)"xyz");  

There are cases where the compiler won't know which overload to select, for example:

void method2(string x, object y); void method2(object x, string y);  method2("xyz", "abc"); 

In this case the compiler doesn't know which overload to pick, because neither overload is clearly better than the other (it doesn't know which string to implicitly downcast to object). So it will emit a compiler error.

like image 54
Erik Avatar answered Sep 23 '22 12:09

Erik