TryCast operand must be reference type

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

The code below generates a compile error on line 3 (dim d...)

Dim o As Object = "1900-01-01"
Dim s As String = TryCast(o, String)
Dim d As DateTime = TryCast(o, DateTime)

The error is : TryCast operand must be reference type, but 'Date' is a value
type.

How can I resolve this?

The second line of code does not generate a compile error at all.

Thanks.

Leo Leys
 
Hello,

Yes, TryCast can only work with reference types because it needs to be
able to return Nothing in case the cast fails and you can't set a value
type to Nothing. You need to use CType instead.

Dim d As DateTime = CType(o, DateTime)

Kelly
 
I'm used to C# and therefore I'm not too up to date with VB.Net syntax.

However, you should not try a cast operation in your case (a cast is used to
convert between compatible type (types for which an implicit or explicit
convertion is defined).
Your second line works simply because your "o" object is a string and you
convert it to a string. In any case, because ToString() method is defined
for all object, you will be always able to cast to a string. The 3rd line
has a problem. Your "o" object has no knowledge about how to convert to a
DateTime type.


What you should do is a parse operation:

Module Module1
Sub Main()
Dim str As String = "1900-01-01"
Dim dt As DateTime
If (DateTime.TryParse(str, dt)) Then
Console.WriteLine(dt)
End If
Console.ReadLine()
End Sub


- José
 
Thanks for your answer. In my application I'm dependent on user input, which
is stored in the variable o.
CType is not suitable for me because it throws an exception if the o
variable contains an invalid date string.
Kind regards
Leo Leys
 
Hi,
Thanks for your reply. The tryparse method is exactly what I needed.
Many thanks.
Kind regards
Leo Leys
 
Back
Top