-
-
Save jgauffin/f3faac68d63a610e3ffd to your computer and use it in GitHub Desktop.
As extension method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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