Skip to content

Instantly share code, notes, and snippets.

@jgauffin
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgauffin/f3faac68d63a610e3ffd to your computer and use it in GitHub Desktop.
Save jgauffin/f3faac68d63a610e3ffd to your computer and use it in GitHub Desktop.
As extension method
public static class ObjectExtensions
{
public static T As<T>(this object instance)
{
if (instance == null) return default(T);
var casted = instance as T;
if (casted == null)
throw new ArgumentException("Cannot cast '" + instance.GetType().FullName + "' to '" + typeof(T).FullName + "'.");
return casted;
}
}
@Dekryptid
Copy link

The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint. Fix: public static T As(this object instance) where T : class

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment