This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Richard Siddaway Richard Siddaway 3 months ago.

  • Author
  • #66861
    Profile photo of rkbalaji

    could anyone clarify me on this question.

    Are there any difference between syntax [Timespan]$var = new-timespan & $var = new-timespan?

    if yes what is the difference.

  • #66867
    Profile photo of Sam Boutros
    Sam Boutros

    When using:

    [Timespan]$var = new-timespan

    You're specifically spelling out (casting) the $var variable type, as System.Timespan data type. Whereas,

    $var = new-timespan

    You're letting PowerShell determine what data type to assign to $var.

    PowerShell usually does a good job at assigning the right data type, but in some cases you may want to specify exactly the data type to use.

    For example:

    [int]1 + [int]1

    returns 1, while

    [string]1 + [string]1

    returns 11 🙂

  • #66886
    Profile photo of Richard Siddaway
    Richard Siddaway

    To answer your question directly – NO

    PS> [timespan]$var = New-TimeSpan
    PS> $var.GetType().Fullname
    PS> $var1 = New-TimeSpan
    PS> $var1.GetType().Fullname

    As the code shows in both cases you have a Timespan object. PowerShell is very good at managing the type of the objects it deals with. In your first case the cast to TimeSpan you do is actually redundant because New-Timespan creates a timespan object. The cast is therefore ignored.

    As a generalisation when you create an object from a cmdlet you don't need to cast the variable to that type.

    You can test the type of any object

    PS> $var -is [timespan]
    PS> $var1 -is [timespan]

You must be logged in to reply to this topic.