I’m trying to create a a simple function in VB.net which will take a few parameters for use with TryCast.
My goal is to have a function I can use in place of TryCast which instead of returning Nothing when it fails it should return DbNull.
I just can’t seem to get anything to work despite much searching.
Thanks.
The problem is that you have to have some specific return type for your function. So you can write a function with a signature like this:
But you will never be able to make it do what you want, because the type of
Tis never going to be DBNull (okay, maybe it could happen, but hopefully you get the idea).Put another way, the type system blocks this. On the one hand, you want to be perfectly explicit about the return type (hence, the cast). On the other hand, you want to be able to return a completely different type. .Net does not allow this, even with dynamic typing. Either a method returns a single fixed type, or it is not declared to return a type at all.
With
Option Explicitturned off, you might be able to go for something like this:However, I don’t think this will do what you want, either, because now the returned value is effectively the same as object, and you lose the benefit of any casting.
It works with the normal TryCast() for
Nothing, because Nothing can be assigned to any type. DBNull is itself a fixed type, and so is not as flexible.