Reputation: 129
It's possible to make a extension method for Object but not being able to use it on any derived class?
What a want is some general utilities to convert objects to certain types handling common exceptions. Ej. method for converting object to string but changing null to empty string and trimming white spaces.
object obj = ...
// I want to use de the method when the object is 'casted' as 'object':
string strValue = obj.ToStringTrim();
// But not be able to use it in any subclass. Ej. en this string:
strValue.ToStringTrim();
I know this is a tricky syntactic sugar and I supose the answer will be negative, and I should make a custom utility class for this kind of conversions, but just curious if it's possible...
EDIT
I know this is against inheritance, but I just wanted a hack, syntactic sugar or whatever... And already exists some in C# ;). And, why is this an issue? Well, it's not really an issue, but I don't want to have so much bloat on the autocomplete
Upvotes: 0
Views: 247
Reputation: 460098
No, that's not possible because that's not how inheritance works. A string is an Object. Period! But why is that an issue? Don't use this extension with a string if you don't want.
However, the extension method could be implemented as:
public static string ToStringTrim(this Object obj)
{
return obj?.ToString().Trim() ?? "";
}
If obj
is already a string
then this is a no-op because String.ToString
is implemented as return this
.
Upvotes: 4