Brij
Brij

Reputation: 13141

DateTime in VB.NET and C#

I have two questions:

  1. Date and DateTime : Are they different or same in VB ?

  2. DateTime can be assigned Nothing in VB, where as it cannot be assigned null in C#. Being a structure it cannot be null. So why is it being allowed in VB ?

---VB.NET-----

Module Module1

    Sub Main()
        Dim d As Date = Nothing
        Dim dt As DateTime = Nothing

        d = CType(MyDate, DateTime)


    End Sub

    Public ReadOnly Property MyDate As DateTime
        Get
            Return Nothing
        End Get
    End Property

End Module

---C#.NET-----

class Program
    {
        static void Main(string[] args)
        {
            DateTime dt = null;//compile time error            
        }
    }

Upvotes: 7

Views: 6305

Answers (3)

John Koerner
John Koerner

Reputation: 38077

In vb.net Date is simply an alias for DateTime.

Some of aliases that exist in VB are there for legacy purposes to help with conversions from vb6 applications.

Upvotes: 3

Tilak
Tilak

Reputation: 30698

In c# You can use default keyword

DateTime dt = default(DateTime);

Date and DateTime are same in VB.NET. Date is just alias of DateTime

Upvotes: 3

Tim Schmelter
Tim Schmelter

Reputation: 460138

Nothing in VB.NET is not the same as null in C#. It has also the function of default in C# and that is what happens when you use it on a structure like System.DateTime.

So both, Date and DateTime refer to the same struct System.DateTime and

Dim dt As Date = Nothing 

actually is the same as

Dim dt = Date.MinValue

or (in C#)

DateTime dt = default(DateTime);

Upvotes: 14

Related Questions