Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C#
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
Updated 27-May-12 4:15am
v2

1 solution

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


Consider the following:
C#
public class Test1 {
   public Test1(string somestring) { }
}

public class Test2<T1> where T1 : new() {
}

Now if I try to define an instance
C#
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>'  
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 28-May-12 1:51am    
Correct! My 5.
--SA
Wendelius 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900