Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good practice to create extension methods that apply to System.Object?

I'm wondering whether I should create extension methods that apply on the object level or whether they should be located at a lower point in the class hierarchy. What I mean is something along the lines of:

public static string SafeToString(this Object o) {
    if (o == null || o is System.DBNull)
        return "";
    else {
        if (o is string)
            return (string)o;
        else
            return "";
    }
}

public static int SafeToInt(this Object o) {
    if (o == null || o is System.DBNull)
        return 0;
    else {
        if (o.IsNumeric())
            return Convert.ToInt32(o);
        else
            return 0;
    }
}
//same for double.. etc

I wrote those methods since I have to deal a lot with database data (From the OleDbDataReader) that can be null (shouldn't, though) since the underlying database is unfortunately very liberal with columns that may be null. And to make my life a little easier, I came up with those extension methods.

What I'd like to know is whether this is good style, acceptable style or bad style. I kinda have my worries about it since it kinda "pollutes" the Object-class.

Thank you in advance & Best Regards :)

Christian

P.S. I didn't tag it as "subjective" intentionally.

like image 577
Christian Avatar asked Mar 10 '10 14:03

Christian


1 Answers

Extension method pollution of System.Object can be quite annoying in the general case, but you can place these extension methods in a separate namespace so that developers must actively opt in to use those methods.

If you couple this with code that follows the Single Responsibility Principle, you should only have to import this namespace in relatively few classes.

Under such circumstances, such extension methods may be acceptable.

like image 72
Mark Seemann Avatar answered Oct 01 '22 23:10

Mark Seemann