I was wondering if there is any way to access the expected data type within a function similar to an event arg. I am doubtful that this is possible, though it would be an excellent feature.
I frequently work with (old and disorganized)Mysql databases creating interfaces through VB.Net. Often I will have an optional field which contains a NULL value in the database. I am frequently dealing with errors due to NULL and dbnull values in passing data to and from the database.
To complicate things, I often am dealing with unexpected datatypes. I might have an integer zero, a double zero, an empty string, or a string zero.
So I spend a fair amount of code checking that each entry is of the expected type and or converting NULLs to zeros or empty strings depending on the case. I have written a function ncc(null catch convert) to speed up this process.
Public Function ncc(obj As Object, tp As Type) As Object 'Null Catch Convert Function... My function works great, but I have to manually set the type every time I call the function. It would be so much easier if it were possible to access the expected type of the expression. Here is an example of what I mean.
Dim table as datatable adapter.fill(table) dim strinfo as string dim intinfo as long strinfo = ncc(table.Rows(0).Item(0),gettype(String)) 'here a string is expected intinfo = ncc(table.Rows(0).Item(0),gettype(Long)) 'here a long is expected It would be so much more efficient if it were possible to access the expected type directly from the function.
Something like this would be great:
Public Function ncc(obj As Object, optional tp As Type = nothing) As Object If tp Is Nothing Then tp = gettype(ncc.expectedtype) That way I do not have to hard code the type on each line.
strinfo = ncc(table.Rows(0).Item(0))
dim intinfo as integer, you call the method passingGetType(Long), then the method returnsObject(??) -- Do you already know the Type of these values? If you do, maybe you want something likePublic Function ncc(Of T)(obj As Object) As T If obj Is DBNull.Value Or obj Is Nothing Then Return CType(Nothing, T) Return CType(obj, T) End Function, calling it as, e.g.,dim someInt = ncc(Of Integer)(table.Rows(0)(0)). If you accept to getNothingfrom reference type objectsSubso that the target is a parameter to it. You could even make it generic, and type inference would make it so that you wouldn't have to specify the destination type explicitly.