Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Generics
Hi,
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
v2

1 solution

Rate this: bad
good
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>'  
  Permalink  
v2
Comments
SAKryukov at 28-May-12 1:51am
   
Correct! My 5.
--SA
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 Sergey Alexandrovich Kryukov 520
1 Mathew Soji 315
2 Shweta N Mishra 269
3 BillWoodruff 240
4 OriginalGriff 235
0 OriginalGriff 6,168
1 Sergey Alexandrovich Kryukov 5,818
2 DamithSL 4,988
3 Manas Bhardwaj 4,539
4 Maciej Los 3,775


Advertise | Privacy | Mobile
Web03 | 2.8.1411019.1 | Last Updated 27 May 2012
Copyright © CodeProject, 1999-2014
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