2

I know that PowerShell function calls don't need specific parentheses like C#, but when I try to call .NET class functions, it seems parentheses are always needed, like:

[Int32]::Parse("12")

So is this a syntax rule?

briantist
  • 39,669
  • 6
  • 64
  • 102
vik santata
  • 2,525
  • 5
  • 24
  • 47
  • When you say "braces", are you referring to the square brackets (`[]`) around the type name, or the parentheses (`()`) around the arguments? – Mathias R. Jessen Aug 05 '15 at 07:47

2 Answers2

2

The way you refer to a .NET type in general is to put the typename in square brackets e.g. '' -is [string]. Although '' -is 'string' works as well, I find it easier to tell that a .NET type is being referred to when square brackets are used.

The way you refer to static type members is to use :: on the type specifier as in [System.Int32]::Parse("12"). Note that PowerShell will prepend System. your typename, if it can't find it as you've specified. This makes for a nice shortcut. There are also type accelerators that appear the same way e.g. [int]::Parse("12").

Keith Hill
  • 173,872
  • 36
  • 316
  • 347
1

Yes, it is a rule. More specifically, when you call a method on an object (as opposed to a cmdlet or standalone function), you always use what you are calling braces () and you separate your arguments with commas ,:

# A cmdlet: no use of (), parameter names and values separated by spaces
$obj = New-Object -TypeName PSObject -ArgumentList @{Name='hello'}

# A method: () are used even with no arguments
$obj.GetType()

Note that in English these are much more commonly referred to as parentheses, and braces typically refer to curly braces which are these: {}.

briantist
  • 39,669
  • 6
  • 64
  • 102
  • parenthesis, parentheses, very nice English hit. – vik santata Aug 05 '15 at 08:22
  • 1
    IIRC, since PowerShell v3 your can omit parentheses if you passing single script block literal. For example `[Int32]::Parse{12}` is the same as `[Int32]::Parse({12})`. – user4003407 Jan 21 '19 at 17:42
  • @PetSerAl nice, I've seen that for the `.ForEach` and `.Where` methods that were added and thought it was specific to those. I guess it makes more sense that they would do it for all methods, even if they had those 2 in mind at the time. I think it's important to note though that in the case of something like `[int]::Parse{12}` the scriptblock is _not_ being executed. It's being cast to the argument type, in this case string, so it works with `{12}`, it won't work with `{12*2}` for example. – briantist Jan 21 '19 at 17:48