简体   繁体   中英

Extension methods for Object but not derived classes

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM