Click here to Skip to main content
11,806,818 members (57,753 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: Generics
I have been using generics for quite a while and have already used them extensively.Recently when i was working on a project involving generics some thing struck me which i want somebody to please clarify. Suppose i declare a class as following:

public class Stack<t> where T : IComparable,new()

Here, the class which takes the position of T should implement IComparable interface and should also implement a default constructor. However we also know the fact that if we don`t provide a default constructor, the compiler automatically inserts a default constructor. So whats the use of writing a "new()" constraint on the generic class ?
Posted 27-May-12 4:14am
Edited 27-May-12 4:15am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

That means, phe parameterless constructor must exist, one way or another.

Consider the following:
public class Test1 {
   public Test1(string somestring) { }
public class Test2<T1> where T1 : new() {
Now if I try to define an instance
Test2<Test1> testInstance = new Test2<Test1>();
That would fail with
'App.Test1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T1' in the generic type or method 'App.Test2<T1>'  
SAKryukov at 28-May-12 1:51am
Correct! My 5.
Mika Wendelius at 1-Jun-12 0:44am
Thanks :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 ppolymorphe 245
1 OriginalGriff 150
2 George Jonsson 145
3 CPallini 100
4 Abhinav S 80
0 OriginalGriff 3,380
1 Maciej Los 1,990
2 CPallini 1,915
3 KrunalRohit 1,907
4 ppolymorphe 1,317

Advertise | Privacy | Mobile
Web02 | 2.8.151002.1 | Last Updated 27 May 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100