# Thursday, 28 December 2006
« New Snapshot | Main | IKVM 0.32 Released »
Object Schizophrenia

Early on in the design of IKVM, I decided that I didn't want to use wrapper objects to bridge the Java and .NET type systems as this leads to either object identity problems (and I just found out that this is sometimes called object schizophrenia and that triggered this post) or horrible performance.

By contrast, J# does use wrapper objects in a least one case and this does indeed lead to object schizophrenia:

public class Program
{
  public static void main(String[] args)
  {
    String foo = "Foo";
    Comparable comp = foo;
    System.out.println(foo == comp);
  }
}

Compiling this Java code with Visual Studio 2005 and running it produces false, while it clearly should print true.

While IKVM doesn't suffer from this, there is a somewhat related problem to look out for when using IKVM ghost interfaces from a .NET language:

using System;
using java.lang;

public class Program
{
  static void Main(string[] args)
  {
    CharSequence seq = "foo";
    object obj1 = seq;
    object obj2 = seq;
    Console.WriteLine(obj1 == obj2);
  }
}

Running this C# app produces False. This is because CharSequence is a ghost interface and represented by a value type. Assigning it to a local variable of type object boxes the value type instead of giving the underlying string object. Note that this only applies to ghost interfaces (i.e. java.lang.CharSequence, java.lang.Cloneable and java.io.Serializable). To fix this problem, you have to explicitly unwrap the object from the value type:

CharSequence seq = "foo";
object obj1 = seq.ToObject();
object obj2 = seq.ToObject();
Console.WriteLine(obj1 == obj2);

Unfortunately .NET doesn't have any mechanism for a value type to prevent (implicit) boxing or defining a custom implicit object conversion operator.

Thursday, 28 December 2006 14:07:23 (W. Europe Standard Time, UTC+01:00)  #    Comments [2]