(2003 to 2005)

Casting, boxing, etc.

Fri Jan 30 21:04:00 UTC+1100 2004


I'm trying to figure out if its OK to create a new object when I specify my own custom implicit casts.

I guess that you have to create a new object if the object is not already of the correct type, which is interesting, because that means that if you cast an object it will cause an objects constructor to execute. If a cast is implicit that this is happening may not be very clear. I have never seen a document that specifies the best practice for using implicit/explicit cast operators.

From my way of thinking it seems that an implicit cast should return the same reference. But if it did, then no custom implicit cast would need to be defined! So I guess that if you use implicit casts you must do so with caution.

Check out this sample code, it demonstrates some interesting things:

  public class EntryPoint {
    public static void Main(string[] args) {
      int i = 0;
      Console.WriteLine(Object.ReferenceEquals(i, i)); // false
      MyClass c = new MyClass();
      Console.WriteLine(Object.ReferenceEquals(c, (MyBase)c)); // true
      Console.WriteLine(Object.ReferenceEquals(c, (string)c)); // false
      Console.Write("Press ENTER to exit.");
  public class MyBase {}
  public class MyClass : MyBase {
    public static explicit operator string (MyClass value) {
      return "MyClass";

Since System.Object defines ToString() I wonder why it doesn't define an explicit cast to a string? I'm glad it doesn't of course (which is probably why it doesn't) but it is all very interesting..

The reason that I want to specify an implicit cast is because I have some immutable objects that model a single value. For example these two lines of code function identically:

person.PrimaryKey = new PersonKey(123);
person.PrimaryKey = 123;

Is that a good thing, or a bad thing?


Copyright © 2003-2005 John Elliot