0

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

1 Answer 1

3

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) 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Nico, I have tried 'As New' and 'As Structure' and then I get the following error.. Type argument 't' does not satisfy the 'Class' constraint for type parameter 'T'
Then the function also expects t to be a class. See the edit.
Ah thank you very much :D I will mark as an answer (cant for 3 mins)!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.