Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Generic Parameter vs Object type parameter [duplicate]

Tags:

c#

.net

I have two overloaded methods one is expecting object type parameter and other generic params list. I'm trying to understand that when which function will be called. I'm passing string object and it's calling generic params method.

class Program
{
    static void Main(string[] args)
    {
        string s = "string";
        Invoke(s);
        Console.ReadLine();
    }

    static void Invoke(object s)
    {
        Console.WriteLine("Object param invoked");
    }

    static void Invoke<T>(params T[] values)
    {
        Console.WriteLine("Params method invoked");
    }
}

It's giving output as: 'Params method invoked'.

But I'm not sure why always this method called.I also tried with passing int parameter but again params method invoked. Please if anyone can explain this for me. Thanks.

like image 210
Rana Mujahid Avatar asked May 19 '26 07:05

Rana Mujahid


1 Answers

In short, type T is more specific than Object because Invoke<string> is a valid invocation.

like image 92
madreflection Avatar answered May 21 '26 19:05

madreflection



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!