Error in Generic method: 'T' does not contain a definition for...

J

J Miro

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 = "";
}
}
//-----------------------------------
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
J

J Miro

Thanks so much Nicholas for your prompt response.

Jay.

Nicholas Paldino said:
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]
- (e-mail address removed)

J Miro said:
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 = "";
}
}
//-----------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top