I have a situation (Deserializer) where I have the System.Type of something that I know inherits from IList. From this method, I need to give back an instance of this type and make sure it has x elements, all filled with the default value.
Simplified code:
Public Function GetIListInstance(theType as System.Type) as IList
...
End Function
When the IList is a simple array, the solution is also simple; the type name ends with []
Making the code:
Public Function GetIListInstance(theType as System.Type) as IList
If theType.Name.EndsWith("[]") Then
Return theType.InstantiateArray(3) //return an array with 3 empty elements
Else
//not an array
...
End If
End Function
When the IList is something else, I can make an instance of it, and use the IList interface to add the 3 elements:
Public Function GetIListInstance(theType as System.Type) as IList
If theType.Name.EndsWith("[]") Then
Return theType.InstantiateArray(3) //return an array with 3 empty elements
Else
//not an array, code for .Net: Activator.CreateInstance
Dim MyList = TheType.Instantiate
For i = 1 to 3
DirectCast(MyList, IList).Add(...)
Next
Return MyList
End If
End Function
Then, I only need to know what the type of the elements of this IList is.
When the list isnât empty, this would be simple. But in this case, as we just created the list, it IS empty.
In .Net, I can get a copy of the underlaying array of the IList (which will be an empty array), and get the type of this array:
Dim UnderlayingArrayType = DirectCast(MyList, Dynamic).ToArray.GetType
And then I can create a new array with 1 uninitialized element; the value of this element is the default value that I need:
Dim DefaultValue = DirectCast(UnderlayingArrayType.InstantiateArray(1), IList).Item(0)
So the complete code becomes:
Public Function GetIListInstance(theType as System.Type) as IList
If theType.Name.EndsWith("[]") Then
Return theType.InstantiateArray(3) //return an array with 3 empty elements
Else
//not an array, code for .Net: Activator.CreateInstance
Dim MyList = TheType.Instantiate
//get the type of the underlaying array
Dim UnderlayingArrayType = DirectCast(MyList, Dynamic).ToArray.GetType
//get a default value for this array
Dim DefaultValue = DirectCast(UnderlayingArrayType.InstantiateArray(1), IList).Item(0)
For i = 1 to 3
DirectCast(MyList, IList).Add(DefaultValue)
Next
Return MyList
End If
End Function
So far, so good - this works when compiled to .Net
The problem
ToArray does not exist when I compile to Island, so the code to get the default value doesnât work here.
The question
How do I get the default value for an item of an IList when compiling for Island?