O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Default Constructor Constraint

Besides generic constraints expressed based on interfaces or base classes, a few other techniques are available. One is the new constraint, expressing the requirement to have a default constructor available for a certain type parameter:

class Factory<T> where T : new() {    ...    public T CreateInstance() {        return new T();    }}

Obviously, the preceding Factory<T> type’s CreateInstance method doesn’t provide any value over direct instantiation of an object from the outside. It’s merely a way to show how the expected constructor syntax can be used in conjunction with a type parameter as long as that parameter is properly constrained. From the outside, this type would be used ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required