Why Generic Template Method Paramter Is Calling Not Object

Posted by Prtkaggrwl under C# on 8/25/2015 | Points: 10 | Views : 328 | Status : [Member] | Replies : 1
Why below code is Writing B not A.

namespace console
{
class Program
{
static void Main(string[] args)
{
FnTest(1);
Console.ReadLine();
}

public static void FnTest(object a)
{
Console.WriteLine("A");
}
public static void FnTest<T>(T a)
{
Console.WriteLine("B");
}


}
}




Responses

Posted by: Shreedar on: 8/25/2015 [Member] Starter | Points: 25

Up
0
Down
Hi

The name itself is saying generic.
That means any datatype it can be int, string and char.
In program FnTest(1); //here argument represents it is an integer type.
So that integer will go to the generic method. Giving you the output from generic method.

Where as declare a object type like below.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace generic_and_object_ex
{
class Program
{
public static void Main(string[] args)
{
Object a = 1;
Func(a); // argument is object type
Func(1); // argument is integer type
Console.ReadKey();
}
public static void Func(Object b)
{
Console.WriteLine("am from object");
}
public static void Func<t>(t b)
{
Console.WriteLine("am from generic");
}
}
}

out put:
am from object
am from generic

Hope you understood.
Mark the answer, if you are satisfied.

Regards

Sridhar Thota.
www.dotnet-sridhar.blogspot.com

Prtkaggrwl, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response