I’m trying to check if a variable has been defined as a nullable Guid. eg.
Dim myGuid As Nullable(Of Guid) or Dim myGuid As Guid?
It seems doing a myGuid.GetType returns the underlying type, that is type Guid, not Guid?. So testing myGuid.GetType Is GetType(Guid?) always returns False.
How do I find out if myGuid is a nullable type?
Ed: I can do the following, which correctly returns True for “Guid?” and False for “Guid”:
Not Nullable.GetUnderlyingType(GetType(Guid?)) Is Nothing
The problem is that I don’t know how to retrieve the nullable type from the variable itself, in order to test it. I’ve only been able to get the underlying (non-nullable) system type.
Ed: Explanation of why I need to know. 🙂
I’ve written a db helper function. I pass it an object comprised of public members, representing the row data of a table. The members are the table columns.
Using reflection, I loop through these public members to create an INSERT statement for a command object and populate its parameters with the values in those members. So far so good.
But now there’s a table which has a uniqueidentifier column which I must not populate from the row object, as it defaults to “NEWID()” (using SQL Server 2008). Instead of skipping all Guid columns, which would be easy, I only want to skip ones defined in the row data class as “Guid” (non-nullable).
Basically, I’m using the Guid? (Nullable) type to indicate it’s ok to populate that uniqueidentifier column with data. If it’s non-nullable, that tells me to skip it because the column has a NEWID() default value.
Hope that makes sense. If there’s a better way of me knowing which guid columns to skip and which to populate, I’d be eager to know. This is just an approach I thought would be doable.
Found a solution! Seems it’s impossible to determine if a variable alone is nullable but, as long as it’s a member of a class, reflection can be used like this:
The class:
The code:
The output:
Thanks to all for your responses.