2

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?

2 Answers 2

1

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 }); } 
Sign up to request clarification or add additional context in comments.

1 Comment

This works. I didn't know that implicit and explicit operators had pre-defined names. All I have to do now is create extension function object.TryCast. Thanks Lee!
0

Lee gave an answer. I tested it by creating an extension method to try to cast any object to any type as long as the object has either an implicit or an explicit cast operator to the requested type.

public static class ObjectExtensionTryCast { public static bool TryCast<T>(this object o, out T castedValue) { MethodInfo castMethod = new string[] { "op_Implicit", "op_Explicit" } .Select(methodName => o.GetType() .GetMethod(methodName, BindingFlags.Static | BindingFlags.Public, null, new[] { o.GetType() }, null)) .Where(method => method.ReturnType == typeof(T)) .FirstOrDefault(); bool canCast = castMethod != null; castedValue = canCast ? (T)castMethod.Invoke(null, new object[] { o }) : default(T); return canCast; } } 

Usage:

object o = GetMyObject(); int i; System.Drawing.Point p; DBSet dbSet; bool intCasted = o.TryCast(out i); bool pointCasted = o.TryCast(out p); bool dbSetCasted = o.TryCast(out dbSet); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.