What is the difference between typeof(), GetType() and IS in C# and VB.NET

What is the difference between typeof(), GetType() and is?

  • typeof() takes a type name specified at compile Time.
  • GetType() gets the Type of an Object at runtime
  • is returns true if an instance is in the inheritance tree. Since the is Keyword is casting the object, you should use it with care.
  • here is an example.

    class Employee { } 
    class Developer : Employee { }
    
    void PrintTypes(Employee e) { 
        print(e.GetType() == typeof(Employee)) // false 
        print(e is Employee)                   // true 
        print(e.GetType() == typeof(Developer))    // true
    }
    

    How to get Hours Difference of 2 Dates in C# and VB.NET

    To get Hours Difference of 2 Dates in C# and VB.NET you can use the following snippet.

    Sample C#

    /// <summary>
    /// Returns the Hour Difference of two Datetimes as Double Value.
    /// </summary>
    /// <param name="dateOne">The original date.</param>
    /// <param name="dateTwo">The Datei to be Checked against the Original Date.</param>
    /// <returns></returns>
    public static Double DifferenceInHours(this DateTime dateOne, DateTime dateTwo)
    {
    	return (dateOne - dateTwo).TotalHours;
    }
    

    Sample VB.NET

    ''' <summary>
    ''' Returns the Hour Difference of two Datetimes as Double Value.
    ''' </summary>
    ''' <param name="dateOne">The original date.</param>
    ''' <param name="dateTwo">The Datei to be Checked against the Original Date.</param>
    ''' <returns></returns>
    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function DifferenceInHours(dateOne As DateTime, dateTwo As DateTime) As [Double]
    	Return (dateOne - dateTwo).TotalHours
    End Function
    

    As always, this extension method has been added to the Github Fesslersoft.Extensions Repository

    How to get the seconds between two dates in Python

    To get the seconds between two dates in Python you can use the following snippet.

    Sample Python

    import datetime
    import time
    
    def DateDiffSeconds(dateOlder, dateNewer):
      timedelta = dateNewer - dateOlder
      return timedelta.days*24*3600 + timedelta.seconds
    
    dateOlder = datetime.datetime(2014,07,01,00,00,00)
    dateNewer = datetime.datetime(2014,07,02,11,30,00)
    print DateDiffSeconds(dateOlder,dateNewer)