Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to explicitly specify the size of an array parameter passed to a function

I have a function which accepts a parameter named IV. Is there anyway that I can explicitly specify the size of the parameter IV to be 16 ?

public AESCBC(byte[] key, byte[16] inputIV)
{

   //blah blah

}

The above is of course not working. Is it possible? I know I can check it inside the function and throw an exception but can it be defined in the function definition ?

like image 398
Ranhiru Jude Cooray Avatar asked Jul 10 '10 06:07

Ranhiru Jude Cooray


2 Answers

You can't, basically. As Jaroslav says, you could create your own type - but other than that, you're stuck with just throwing an exception.

With Code Contracts you could express this in a form which the static checker could help with:

Contract.Requires(inputIV.Length == 16);

Then the static checker could tell you at build time if it thought you might be violating the contract. This is only available with the Premium and Ultimate editions of Visual Studio though.

(You can still use Code Contracts without the static checker with VS Professional, but you won't get the contracts.)

Plug: Currently the Code Contracts chapter from C# in Depth 2nd edition is available free to download, if you want more information.

like image 162
Jon Skeet Avatar answered Oct 18 '22 15:10

Jon Skeet


You cannot specify the size of the array parameter in the method declaration, as you have discovered. The next best thing is to check for the size and throw an exception:

public AESCBC(byte[] key, byte[] inputIV)
{
   if(inputIV.Length != 16)
       throw new ArgumentException("inputIV should be byte[16]");

   //blah blah

}

Another option it to create a class that wraps byte[16] and pass that through.

like image 45
Oded Avatar answered Oct 18 '22 16:10

Oded