Fixed array as parameter

I have a web service with an array as a parameter. The problem is that I want the user to send me an array of 15 entries. Of course, if they sent me a larger array, I could write code to get the first 15, but I don't want to do this. I would like the user to understand that we need 15 and only 15 records and no more.

The only way I know to initialize an array with a fixed value is to instantiate and I cannot do this as a parameter.

Maybe an array as a parameter is not the best option? Any ideas?

+7
source share
6 answers

You cannot control the length of the input array for your operation, but you can add a dynamic check (i.e. throw an ArgumentException if the user passes an array of a different length). Another option would be to simply have 15 parameters for your operation, but it might not be too readable if the parameters are connected and the array will make more sense.

+9
source

In WSDL / XSD for a service, you can specify minOccurs and maxOccurs of 15. As in:

 <xsd:element name="item" minOccurs="15" maxOccurs="15"> <xsd:complexType> ... </xsd:complexType> </xsd:element> 
+2
source

You can throw an ArgumentException if the size of the array is incorrect.

+1
source

The only language features here will be

1. List of arguments

 public void Foo<T>(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9, T t10, T t11, T t12, T t13, T t14, T t15) { internalFoo(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15); } private void internalFoo(params T[] arr) { // profit } 

2. Structure Parameter object parameters

 struct FooParams<T> { public T t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15; } public void Foo<T>(FooParams<T> fooParams) { // profit } 

3. With # 4.0 Tuples , you must insert tuples with a Tuple<...,Rest> style declaration Tuple<...,Rest> , because the framework library only goes to 8-ape tuples (octuples?)

+1
source

you can specify a description of the webservice function so that the user knows that only 15 elements will be considered, if the use tries to exceed this limit, to exclude an argument or its own exception ... otherwise there is no other way to do this.

0
source

You can use Contract.Requires(arg.Length==15) and hope that the static checker will / will be good enough to catch user errors.

Or you can create a class that wraps the array that it owns. Since the class owns and creates an array, it can control its size.

I prefer the first method in most situations. Sometimes you have to run into runtime errors.

0
source

All Articles