views:

64

answers:

2

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 ?

+1  A: 

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.

Oded
+8  A: 

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.

Jon Skeet
Jon - I just bought your book and I have to say I've never gained so much knowledge for $30. I've preordered the 2nd edition as well. Amazing stuff!
Marko
Note: you need to define the `CONTRACTS_FULL` compilation symbol (if not already defined), otherwise the `Contract.Requires` won't be compiled.
Jaroslav Jandek
@Marko: Thanks, that's a lovely endorsement :) @Jaroslav: Yes, if you're going to use Code Contracts effectively you really need to download the tools which make this sort of thing easy.
Jon Skeet