Nick
Nick

Reputation: 3

Class type as function argument in vb.net

Hi I am using LinqToCsv to load some data from different files into some variables.

I currently have 3 different files and am using classes to easily import these but I want to make the code more generic and I am struggling when it comes to passing in a type as an argument.

I am using code similar to the following:

    Public Class Csv1
        Property AField1 As String
        Property AField2 As String
    End Class

    Public Class Csv2
        Property BField1 As String
        Property BField2 As String
    End Class

    Public Class Csv3
        Property CField1 As String
        Property CField2 As String
    End Class

    Public Module CsvTools
        Private Function GetCsvData(Of t)(fName As String) As IEnumerable(Of t)
            If IO.File.Exists(fName) Then
                Dim cf = New CsvFileDescription With {
                    .SeparatorChar = ",",
                    .FirstLineHasColumnNames = True,
                    .IgnoreUnknownColumns = True
                }
                Dim cc = New CsvContext()
                Return cc.Read(Of t)(fName, cf)
                'This line above gives the compile error:
                ' Type parameter 't' must have either a 'New' constraint or a 'Structure' constraint to satisfy the 'New'
                ' constraint for type parameter 'T'
            End If
        End Function

        Property File1 As IEnumerable(Of Csv1)
        Property File2 As IEnumerable(Of Csv2)
        Property File3 As IEnumerable(Of Csv3)

        Public Sub LoadData()
            File1 = GetCsvData(Of Csv1)("File1.csv")
            File2 = GetCsvData(Of Csv2)("File2.csv")
            File3 = GetCsvData(Of Csv3)("File3.csv")
        End Sub

    End Module

Anyone care to point out what I am doing wrong? I don't want to replicate the GetCsvData code for each different type of file I want to import..

I have googled etc for the answer and everything I have tried throws a different error. Think my brain is melting a bit now can anyone point me in the right direction? thanks

Upvotes: 0

Views: 1135

Answers (1)

Nico Schertler
Nico Schertler

Reputation: 32597

cc.Read(Of t) requires t to have a default constructor, which you did not ensure. Add the constraint to the method declaration:

Private Function GetCsvData(Of t As {Class, New})(fName As String) As IEnumerable(Of t)

Upvotes: 3

Related Questions