Search code examples
c#casting

How toDetermine if an object can be cast to a different type, without IConvertible


I have two unrelated classes: one is not derived from another. The classes do not implement IConvertible. This is why This answer does not work.

Luckily there is an implicit class operator from one class to another.

Example: consider the two following classes

  • System.Data.Entity.DbSet<TEntity>
  • System.Data.Entity.DbSet.

Implicit cast operator:

public static implicit operator DbSet (DbSet<TEntity> entry)

The following works:

DbSet<MyClass> x = new DbSet<MyClass>();
DbSet y = (DbSet) x;         // ok, x properly cast to y

The following does not work:

object x = new DbSet<MyClass>();
object y1 = x as DbSet;      // y1 is null, because not derived from DbSet
object y2 = (DbSet) x;       // throws InvalidCastException

So is it possible to check if an object can be cast to another object without throwing exceptions?


Solution

  • You should be able to search for the conversion method using reflection:

    object set = new DbSet<MyClass>();
    var conv = set.GetType().GetMethod("op_Implicit", BindingFlags.Static | BindingFlags.Public, null, new[] { set.GetType() }, null);
    if (conv != null && conv.ReturnType == typeof(DbSet))
    {
        var rawSet = (DbSet)conv.Invoke(null, new object[] { set });
    }