Monday, 7 January 2013

Instantiating a Generic Type of T

I found a requirement recently where I needed to Instantiate a new instance of a Generic Type.

Ordinarily we would declare a new instance of a class using a Generic Type using something like;

Public Class ViewModel_Class(Of T)

However, If we then try to create a new Object of Type T by performing the following…



Dim MyNewObject As New T

…an error will be produced, reporting “New cannot be used on a type parameter that does not have a new constraint”.

This error is telling us that the Compiler doesn’t know if the Generic Type has an implicit “New” Sub, which is can use to Instantiate a new Object.

So, we need to add a Generic Type Constraint for a New Sub by specifying this when we declare our Generic Type;



Public Class ViewModel_Class(Of T as {New})

This tells the compiler that whatever Type T is, it will have a New Sub which it can use to instantiate the New Object.

You can read more on this subject on the Microsoft Website at;

http://msdn.microsoft.com/en-us/library/w256ka79(v=vs.110).aspx

No comments:

Post a Comment