C# Generics Problem: MSFT guys may know this

C

consumer62000

Hello All
I found some *issue* with the generics in C#. It looks like an issue to
me :

In C++ the following code compiles fine

class Person
{
public:
char last[10];
};
template <typename T>
class MyClass
{
T x;
public:
void call()
{
char copy[10];
strcpy(copy,x.last);
....
}
};

However a similar code fails to compile in C#
class Person
{
public string lastName;
}
class MyClass<T>
{
private T x;
public void Call()
{
string s = x.lastName;//COMPILER ERROR HERE
}
}

from what I understand, the compiler is not expanding the code ,rather
the code is *expanded* at runtime.
Does it mean you can never access any "function" of T even if you want
to do something like what I did above.
If this is true then it looks like a serious drawback of generics to
me.
because the compiler does a check for T t
}
}
 
T

Ted Miller

You must constrain the type paramter T (use "where" for this).

class Person
{
public string lastName;
}

class MyClass<T> where T : Person
{
private T x;
public void Call()
{
string s = x.lastName;
}
}
 
D

David Browne

Hello All
I found some *issue* with the generics in C#. It looks like an issue to
me :

In C++ the following code compiles fine

class Person
{
public:
char last[10];
};
template <typename T>
class MyClass
{
T x;
public:
void call()
{
char copy[10];
strcpy(copy,x.last);
...
}
};

However a similar code fails to compile in C#
class Person
{
public string lastName;
}
class MyClass<T>
{
private T x;
public void Call()
{
string s = x.lastName;//COMPILER ERROR HERE
}
}

from what I understand, the compiler is not expanding the code ,rather
the code is *expanded* at runtime.

That's exactly right. C++ templates are compiler magic. CLR Generics are
runtime magic. Notice they are CLR Generics, not C# Generics. They are
implemented in the .NET runtime, not the various language compilers.
Does it mean you can never access any "function" of T even if you want
to do something like what I did above.

You absolutely can. You have a couple of options.

Define an interface or base type which has the function and restrict the
generic to the interface.
Like this

interface ISurnamed
{
string LastName
{
get;
}
}
class MyClass<T>
where T : ISurnamed
{
T t = default(T);
void Foo()
{
string s = t.LastName;
}
}

Or, in a pinch, use you can always use reflection or emit a dynamic method
http://codeproject.com/csharp/GenericOperators.asp.

David
 

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