Generics in C# are not like C++, in that the type T is not resolved at
compile-time in order to determine whether or not a class has certain
members. Because of this, you will have to use reflection to call the
member "Name", or you can use a constraint, defining an interface or base
class which exposes the member, like so:
public interface IPerson
{
string Name {get; set;}
}
public class Person : IPerson
{}
static void ShowName<T>(T someObject) where T : IPerson
{
Console.WriteLine(someObject.Name);
}
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
mv*@spam.guard.caspershouse.com
"J Miro" <jm***@yahoo.comwrote in message
news:46**********************@roadrunner.com...
When I call the Generic method ShowName in the following code, I get the
error message "'T' does not contain a definition for 'Name'." Does anyone
know why? Thanks in advance. Jay.
//------------------------------------
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class GenericsTest
{
static void Main(string[] args)
{
Person person = new Person();
person.Name = "John";
ShowName<Person>(person);
}
static void ShowName<T>(T someObject)
{
Console.WriteLine(someObject.Name);
}
}
public class Person
{
public string Name = "";
}
}
//-----------------------------------