List of Quaternions - NullReferenceException with types or type check errors without?

I’m trying to create a list of quaternions. I need to be able to add and remove quaternions at any time, so I don’t want to use an Array. But I seem to be getting NullReferenceExceptions no matter what I do.

Here’s a simple example:

q = Quaternion(1, 0, 0, 0)
print(q.ToString())  # Works fine
qList = [] as List[of Quaternion]
qList.Add(q)  # Crashes here with NullReferenceException: Object reference not set to an instance of an object.

Here’s another example:

q = Quaternion(1, 0, 0, 0)
print(q.ToString())  # Works fine
qList = [q] as List[of Quaternion]
print(qList.ToString())  # Crashes here with NullReferenceException: Object reference not set to an instance of an object.

Note that if I remove as List[of Quaternion] from that second example, it works, but then the compiler only sees qList as a list, so the following then doesn’t work:

def methodThatTakesQList(qList as List[of Quaternion]:
    print(qList.ToString())

q = Quaternion(1, 0, 0, 0)
print(q.ToString())  # Works fine
qList = [q]
methodThatTakesQList(qList)  # The best overload for the method 'methodThatTakesQList(Boo.Lang.List[of UnityEngine.Quaternion])' is not compatible with the argument list '(Boo.Lang.List)'.

If I remove the as List[of Quaternion], this example perfectly works too, but I’d like to actually use some methods of quaternions (IE, multiplying them together) which fails the compilation type-check, since it sees it as me just trying to multiply objects together.

What you are doing there makes not much sense. A List and an array are two seperate things. What you do here is creating an array and then use the as-cast to cast it into a List. However since an array is not a List this cast will fail. And one of the properties of the as-cast is that it will return null if a cast is not possible.

I’m not familiar with boo at all (like most people here). However from what i read the as-cast works the same as in all .NET / Mono languages.

What you actually want is creating an instance of a List. This should look like this:

qList = List[of Quaternion]()

Usually the generic List also has a ToArray method if you need a built-in array from that list. However since boo has it’s own List implementation it might be different.

edit
Little correction :wink: the [] brackets seem to create an untyped List and not an array. Anyways the same problem: a List is not a List[of Quaternion] so an as cast will fail.