Quick tip: Integer parameter validation

Validating your parameters are important. This quick tip is about integer parameters.

As you probably know, there are different types of integer types, but the most common one in use are probably System.Int32. Validating any parameters that use integer parameters are smart, so you don’t get any angry error messages in your script because the value is outside the value range of the type.

The following table shows the different integer types and their minimum and maximum values:

Type Name Minimum Value Maximum Value
Int16 -32768 32767
UInt16 0 65535
Int32 -2147483648 2147483647
UInt32 0 4294967295
Int64 -9223372036854775808 9223372036854775807
Uint64 0 18446744073709551615

Note! When you use [Int] it’s [System.Int32] you are using.

Often you might see this kind of parameter declaration for integers:

[int] $ValueX

This is of course correct, but typically you don’t want negative values and you might rewrite it into this:

[int] $ValueX

But as you can see from my table above, if you only want positive values, you could have used an unsigned integer instead, as these have a minimum value of 0.

But did you know that the all the integer types have two fields called ‘MinValue’ and ‘MaxValue’? These can be used to show, you guessed it, the minimum and maximum values of the type. So the two above examples can be rewritten further like this:

[int] $ValueX

[int] $ValueY

So now you don’t have to memorize the maximum values of the int type anymore (or more usually, look it up online), just use the MinValue/MaxValue fields!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s