Unity Player crash when calling method on covariant generic interface C#

Hi,

I’m having an issue where unity crashes when methods on covariant generic interfaces are called. I’ve comment out any work performed by the methods to confirm it is defiantly the act of calling the methods that causes the crash. Here is a snippet from the crash error log:

Unity Player [version: Unity 4.3.3f1_c8ca9b6b9936]

mono.dll caused an Access Violation (0xc0000005)
in module mono.dll at 0023:100010c6.


Read from location 00000000 caused an access violation.

I’ve searched around the web for similar issues but couldn’t find anything that seemed related. (same result different cause).
As far as I can tell (correct me if I’m wrong) variance in generic interfaces should work with mono in the current version of unity (with the target framework set at .net 4.0).

Here is a snippet of the way I’ve implement the interface in case I’m the cause of the problem… (variable names changed/code cuts for clarity)

//Interface
public interface ICovariant<out T> {

	void TestMethod();
}

//Implemented on Class
public class TestClass<T> :  ICovariant<T> where T : BaseType {

	public void TestMethod() {
		int x = 1;
	}

}

//Called from GameObject Component
public class BaseType : GameBase {

	void Start() {
	
		 ICovariant<BaseType> MethodObject = new TestClass<DerivedType>();
		MethodObject.TestMethod();

	}

}

Is the problem with Unity or myself?
Let me know if you need any further information and thanks for the help in advance. :smile:

Similar problem!

Unity currently targets .NET 3.5, not .NET 4.

It should be noticed though that if you have:

var baseList = new List<BaseType>();

And you want to add derived types to that list you can…

public class DerivedType : BaseType
{
     ////
}
baseList.Add(new DerivedType());

Then when getting the items back out you can do something like:

foreach(var itm in baseList)
{
     if(itm is DerivedType)
     {
             ((DerivedType)itm).SomeMethodInDerivedType();
     }
}

Thanks for the clarification,
This is the direction I ended up going with.

Yup. I can confirm that. Reported to bugtracker as well.

i ran into this also but i couldn’t simplify down to new List<Base>().Add(Derived). I needed a List<Action<Base>> but this requires variants if you want to .Add(Action<Derived>). after thinking about it for several hours i was able to figure out a way to get it to work using List<Action<Type, Base>> plus lambda scope and a cast such as .Add((Type t, Base b) => { if (t == typeof(T)) { action.Invoke((T) b); }}. i thought it was a pretty clever alternative to variants that works with Unity. i haven’t explored it all the way but i suspect it can probably do whatever variants can do, and without using reflection.