Careful with ToString()

by May 22, 2017

Any .NET object has a method ToString() that returns a text representation. This is also what you get when you output an object in a string. However, the value returned by ToString() can vary, and you should never use it to make critical assumptions.

Here is an example – these lines both produce a FileInfo object which represents the exact same file. Only the way how the object was created is different. All object properties are identical. Yet, ToString() differs:

 
PS> $file1 = Get-ChildItem $env:windir -Filter regedit.exe
PS> $file2 = Get-Item $env:windir\regedit.exe

$file1.FullName; $file2.FullName
C:\WINDOWS\regedit.exe
C:\WINDOWS\regedit.exe

PS> $file1.GetType().FullName; $file2.GetType().FullName
System.IO.FileInfo
System.IO.FileInfo

PS> $file1.ToString(); $file2.ToString()
regedit.exe
C:\WINDOWS\regedit.exe  

Twitter This Tip! ReTweet this Tip!