Author Posts

March 21, 2017 at 2:30 pm

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.

March 21, 2017 at 3:00 pm

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 🙂

March 21, 2017 at 5:39 pm

To answer your question directly – NO

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

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]
True
PS> $var1 -is [timespan]
True