C# generics

, May 10, 2003

Don Box has this example about the upcoming C# support for generics:

CLR generics that use members of a type parameter require an explicit predicate on the parameter to ensure that no runtime checks will need to be done.

Here's an example of how this works in C#:



class Bob where T : IHasG {
T t;
public : void f() { t.g(42); }
};


which assumes an IHasG interface that looks more or less like this:


public interface IHasG {
void g(int);
}

which I find awfully disappointing. Not having to have classes derive from a specific abstract base class in C++ to do this has always been one of my favorite C++ features.

On July 21, 2003 10:47 AM, svkoli said:

that’s wrong. generics in C# do not require such an explicite predicate on the parameter, which is called constraint, they can optionally have one more oh them. have a look at: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vbconcprogramminglanguagefuturefeatures.asp

On July 21, 2003 11:30 AM, Stefan Tilkov said:

But they need to have a constraint if I want to call a method on the object - right? That’s how I understand the doc you pointed to, anyway …

On August 5, 2003 11:09 AM, Iulia said:

I have a problem with a program in c#. I have it in java but there is a section where the program generates the numbers randomly. The code in java is : ” for(int j=0; j<size; j++) { int n = (int)(lang.math.random()*99);

If you could help me with these matter i would be very gratefull.

On August 5, 2003 1:37 PM, Stefan Tilkov said:

Iulia, I don’t program in C#, but a quick Google search for “C# random” yields http://www.experts-exchange.com/Programming/ProgrammingLanguages/CSharp/Q_20403988.html, which should help you.

On February 19, 2004 5:02 PM, Blublobb said:

Yes. You need that constraint. Thats whats called “type-safety”.. and not having it was actually one of the reasons why C++ templates sucked so hard.