Tuesday, August 14, 2012

New cannot be used on a type parameter that does not have a new constraint

This is not such an obscure problem as it is just not straight forward to solve. Simply put you cannot instantiate a new instance of a generic object without explicitly saying that the method/class you are trying to do this inside of must allow for it.

Let's Review That Error One More Time
New cannot be used on a type parameter that does not have a new constraint.

Code that will Cause this Error
Private Sub GenericMethod(Of T)(parameter1 As Integer)
 Dim obj As New T() 'This line won't compile because it is not explicitly allowed
 
 Dim strExample As String = obj.GetType().Name

 'Do more stuff...
End Sub
So What This Really Means Is...
The new keyword cannot be used to instantiate an object of type T if the method/class that it is being used in side of did not explicitly define it as a constraint of the method/class.

Code That Will Compile Happily
'By explicitly stating that this method's generic T can be instantiated solves the problem
Private Sub GenericMethod(Of T As {New})(parameter1 As Integer)
 Dim obj As New T()
 
 Dim strExample As String = obj.GetType().Name

 'Do more stuff...
End Sub

Resources
Constraints on Type Parameters VB.Net
Constraints on Type Parameters C#
https://www.google.com/search?q=constraints+on+type+parameters+vb.net
https://www.google.com/search?q=constraints+on+type+parameters+C#

2 comments:

  1. Private Sub GenericMethod(Of T As MyType {New})(parameter1 As Integer) does not work. ???

    ReplyDelete
    Replies
    1. I am not 100% sure about this, but try including your type into the set and separating the types by commas.

      Private Sub GenericMethod(Of T As {MyType, New})(parameter1 As Integer)

      Delete