Is it a good idea to use an extension method on the Object class?
I was wondering if by registering this method if you were incurring a performance penalty as it would b
If you truly intend to extend every object, then doing so is the right thing to do. However, if your extension really only applies to a subset of objects, it should be applied to the highest hierarchical level that is necessary, but no more.
Also, the method will only be available where your namespace is imported.
I have extended Object
for a method that attempts to cast to a specified type:
public static T TryCast(this object input)
{
bool success;
return TryCast(input, out success);
}
I also overloaded it to take in a success
bool (like TryParse
does):
public static T TryCast(this object input, out bool success)
{
success = true;
if(input is T)
return (T)input;
success = false;
return default(T);
}
I have since expanded this to also attempt to parse input
(by using ToString
and using a converter), but that gets more complicated.