Click here to Skip to main content
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 5:14am
Edited 27-May-12 5: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 Maciej Los 600
1 OriginalGriff 455
2 Sascha Lefévre 289
3 Richard Deeming 195
4 Abhinav S 190
0 Sergey Alexandrovich Kryukov 9,693
1 OriginalGriff 9,185
2 Peter Leow 5,112
3 Kornfeld Eliyahu Peter 3,373
4 Maciej Los 2,876

Advertise | Privacy | Mobile
Web04 | 2.8.150327.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