views:

360

answers:

2

Duplicate of about 20 recent questions; someone please link them.

For simple scenarios when should i use one or the other? What are the pros & cons?

What are the recommendations for using extension methods?

EDIT:

Let me give an example. Lets say i have a web relative path represented as a string. Now i want to write a method which 1) Checks if the path begins with '/en/ or '/fr/' 2) if it does not then take the value to prepend from another string.

e.g Extension Method

public static string ToLocaleRelativePath(this string s, string contextPath)
        {
//1. Check if string begins with a locale
//2. If it does not prepend the value extracted from the context path
}

Is such an operation suited for an exteniosn method or should it be a utility?

Thanks

+6  A: 

In your example, a utility class is probably more appropriate, because it makes sense only for strings representing relative URLs, rather than for all strings. By contrast, a method that applied to all (or the huge majority of) strings (say, a Trim or Reverse method (if such things didn't already exist)) would fit nicely as an extension method.

itowlson
A: 

There are some good hints that utility classes are bad because they empower and encourage bad practices contradicting OOP patterns (consider this and this).

zzandy