Is there a better / better way to determine the type of the passed object in VB.NET?
I am still developing this feature, but here is what I intend to do. This function will accept an object and then try to determine its type. There is a specific set of types that I'm looking for: Integer, Boolean, Date, String. I'm pretty private so far, but it seems to work so far:
Private Function DataType(ByVal entry As Object) As ValueType
Try
If IsNumeric(entry) Then
If Integer.Parse(entry) Then
Return ValueType.Number
End If
End If
Catch
End Try
Try
If Boolean.Parse(entry) Then
Return ValueType.Boolean
End If
Catch
End Try
Try
If Not Date.Parse(entry) = Nothing Then
Return ValueType.Date
End If
Catch
End Try
Return ValueType.Text
End Function
a source to share
You will need to decide if you accept "42"
an integer. Object type is still String
!
Try patterns and additional checks with help IsNumeric
can be removed anyway. Just use TryParse-Functions
Dim IntResult As Integer
If Integer.TryParse("42", IntResult) Then
' Parsing succeeded - Result is stored in IntResult '
Else
' Failed! '
End If
When types can be checked at compile time, you can use parameter overloading.
a source to share
I am a C # developer and I am not completely cleaning up your code, but I would use a dictionary to map between an object type and something else - I am assuming you are returning an enum value. Here is a C # example. In real code, a dictionary probably doesn't need to be built on every method call.
public enum ValueType
{
Unknown, Number, Boolean, Date, String
}
public static ValueType DataType(Object o)
{
Dictionary<Type, ValueType> map =
new Dictionary<Type, ValueType>
{
{typeof (Int32), ValueType.Number},
{typeof (Int64), ValueType.Number},
{typeof (Decimal), ValueType.Number},
{typeof (Single), ValueType.Number},
{typeof (Double), ValueType.Number},
{typeof (Boolean), ValueType.Boolean},
{typeof (DateTime), ValueType.Date},
{typeof (String), ValueType.String}
};
if ((o == null) || (!map.ContainsKey(o.GetType())))
{
return ValueType.Unknown;
}
else
{
return map[o.GetType()];
}
}
I had a second look and it looks like you are trying to figure out the type of information stored in a string by parsing it - it won't help in that case.
a source to share