May 10, 2003

C# generics

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.

Readers have left 5 Comments:
Comment from svkoli at Jul 21, 2003 10:47 AM:

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

Comment from Stefan Tilkov at Jul 21, 2003 11:30 AM:

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

Comment from Iulia at Aug 5, 2003 11:09 AM:

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.

Comment from Stefan Tilkov at Aug 5, 2003 1:37 PM:

Iulia, I don't program in C#, but a quick Google search for "C# random" yields http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_20403988.html, which should help you.

Comment from Blublobb at Feb 19, 2004 5:02 PM:

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.

Post a comment (no HTML, please; http://... fragments will be turned into links automatically):









Remember personal info?