Click here to Skip to main content
12,997,210 members (76,239 online)
Rate this:
Please Sign up or sign in to vote.
See more:
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
Updated 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 28-May-12 1:51am
Correct! My 5.
Mika 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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170622.1 | Last Updated 27 May 2012
Copyright © CodeProject, 1999-2017
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