r/PowerShell • u/TTwelveUnits • Nov 22 '24
Question Hashtable syntax
why is it when i declare as hashtable, I can access its properties like an object?
PS C:\Users\john> $obj = @{
>> Name = "John"
>> Age = 30
>> }
PS C:\Users\john> $obj.Name
Johnis this just syntactical sugar, or something? thought i would have to do this:
$obj[Name]
23
Upvotes
View all comments
19
u/surfingoldelephant Nov 22 '24 edited Oct 10 '26
$obj['Name']is syntactic sugar for$obj.Item('Name').Item()in PowerShell is aParameterizedProperty, which is how PS exposes a type's indexer. In .NET,Itemis the default indexer name, but some types use a custom name ([string]'s indexer is namedChars).Internally, PowerShell translates member-access (
$obj.Name) into indexing for most dictionary types during member binding. This was introduced early on for convenience. Namely, because.Nameis easier to type than['Name']. It also means you don't need to differentiate between dictionaries and other types.While convenient, there are quite a few reasons to avoid the feature, at least outside the shell. It's slower, broken with some types of dictionary, less feature rich (no array slicing or access to indexer overloads) and is inconsistently implemented in respect to type-native vs extended type system (ETS) properties.
In general, if you want to write robust code:
[]to access dictionary keys.Don't use
.to access type-native dictionary properties (e.g.,Count,KeysorValues) unless you know for certain the dictionary doesn't contain matching keys.get_Count(),get_Keys(),get_Values()) orpsbase($obj.psbase.Count)instead..to access ETS properties attached to the dictionary (this is rarely needed).