SAP RFC calls and all that empty arrays.

Pretty often I have to do some SAP RFC calls (BAPIs) in my projects.
To retrieve a result structure you often have to pass an empty element of the same type in.
In BizTalk this is pretty easy with a Map. You just “connect” all the elements in the target schema to an existing root node and the transformation engine will do the rest for you creating the structure.

But when you have to create this structure in code you are pretty doomed creating all that empty arrays line by line.

Recently I got pretty tired of this, writing a web service calling a SAP BAPI.

So I wrote the following little code code snippet that does the work for me in a generic way.

private void CreateAllArrays(object o)
{
 o.GetType()
	.GetProperties(System.Reflection.BindingFlags.SetProperty
				| System.Reflection.BindingFlags.Public
				| System.Reflection.BindingFlags.Instance)
	.Where(p => p.PropertyType.IsArray)
	.ToList()
	.ForEach(p => p.SetValue(o, Array.CreateInstance(p.PropertyType.GetElementType(), 0), null));
}

Call the “CreateAllArrays” function passing in the object that has properties of type array of [AnyType] and it will create and set an empty array instance for every property found.

Please feel free to adopt and/or copy it for any kind of use.