-6
using System;
using System.Collections.Generic;

namespace Generics
{
    class Minivan
    {
        public void foo(int z, int x)
        {
            Console.WriteLine("foo with two parameters");
        }
        public void foo(params int[] z)
        {
            Console.WriteLine("foo with two params parameter");
        }
    }
    class D
    {
        public static void Main()
        {
            Minivan car3 = new Minivan();
            car3.foo(10,20); // which method will be called here!!!
        }
    }
}

which foo method is called? and why?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
  • 11
    is it so hard to run this code and see? – Selman Genç Feb 17 '15 at 10:16
  • It is covered explicitly in the C# Language Specification, the section that talks about method overload resolution. If you don't want to read then you of course can just try it. And yes, what you see repeats well and was meant to be intuitive. – Hans Passant Feb 17 '15 at 10:18
  • I think all the "because specs" answers are poor, as they are not referring to any specs nor quoting relevant sections. I think the question is poor because it shows zero research effort. I'm sure this has been asked before, try using the search. – CodeCaster Feb 17 '15 at 10:22
  • 1
    possible duplicate of [How does the method overload resolution system decide which method to call when a null value is passed?](http://stackoverflow.com/questions/5173339/how-does-the-method-overload-resolution-system-decide-which-method-to-call-when) – AFract Feb 17 '15 at 10:23

4 Answers4

9

in a simple sentence "more specific is better than less specific"

so public void foo(int z, int x) will be called.

it is because of method overload resolution rules in C#.

you can read more in this answer

Community
  • 1
  • 1
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
2

Compiler will choose a method with explicit parameters (as said in c# spec). But if you'll call method with 3 params the params implementation'll be called

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Alex Voskresenskiy
  • 2,143
  • 2
  • 20
  • 29
1

To put it simply, the one with the two explicit parameters is chosen here.

I don't claim to know the reasoning behind that decision in the spec, but I would image it goes something like "You went to the trouble to explicitly handle the case where two parameters are passed in, so that would be the only sensible choice of method to choose"

ZombieSheep
  • 29,603
  • 12
  • 67
  • 114
1

this is a simple overload, when you explicitly call the function with two parameters it will call public void foo(int z, int x)

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99