When do you use extension methods, ext. methods vs. inheritance? - c#

We started using C# (.NET 3.0) and I wonder how you guys are using extension methods? When do you use them?
Also, I would appreciate if you also list all dark prerequisites for using them.

Times to use extension methods:
when you don't control the types being extended
where you don't want to force the implementor to provide code that can be done using the existing methods
For an example of the second point; you might have an extension method on IList<T> (for example, Sort) that can be written entirely using the existing IList<T> members... so why force anybody else to write anything? This is the foundation block of LINQ, and allowed Microsoft to provide much more functionality without breaking anything.
Times to not use extension methods:
when polymorphism is critical; you cannot guarantee that your code will be the version that gets executed with an extension method, as methods directly on the type take precedence
when you need access to private/protected members

Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code. This means that if you want to add some methods into the existing String class you can do it quite easily. Here's a couple of rules to consider when deciding on whether or not to use extension methods:
Extension methods cannot be used to override existing methods
An extension method with the same name and signature as an instance method will not be called
The concept of extension methods cannot be applied to fields, properties or events
Use extension methods sparingly....overuse can be a bad thing!

This link http://geekswithblogs.net/BlackRabbitCoder/archive/2010/04/26/c-extension-methods---to-extend-or-not-to-extend.aspx provides good guidance on when to use Extension methods and when not.
To quote from this article:
A good extension method should:
- Apply to any possible instance of the type it extends.
- Simplify logic and improve readability/maintainability.
- Apply to the most specific type or interface applicable.
- Be isolated in a namespace so that it does not pollute IntelliSense.

I use extension methods when it makes sense. If you control a class and its code, you usually don't need extension methods.
If you don't, an extension method might be useful.
One place I frequently use extension methods is for [Flags] enumerations. When you have a flag-based enumeration, there's a rather large expression that's necessary to determine whether or not an enumeration value has a particular flag set. And so I build the following extension method whenever I build a [Flags] enumeration:
[Flags]
public enum MyEnum
{
FlagA,
FlagB,
// etc.
}
public static class MyEnumExt
{
public static bool HasFlags(this MyEnum item, MyEnum query)
{
return ((item & query) == query);
}
}
That way my code looks like:
MyEnum flags = MyEnum.FlagA;
if(flags.HasFlags(MyEnum.FlagA))
{
// handle FlagA
}
Rather than:
MyEnum flags = MyEnum.FlagA;
if((flags & MyEnum.FlagA) == MyEnum.FlagA)
{
// handle FlagA
}

Honestly, I would say it is easier to explain when it is NOT a good idea than when it is a good idea.
I think, the main benefit to extension methods is that they may increase the adoption of your method. This is because the user will not have to instantiate an instance of another class in order to use your method and intellisense will advertise your method when a developer is looking for methods for the class you are extending. This could be important if you are trying to get other developers to follow a new standard in your company.
When contemplating whether or not to create an extension method, remember the SOLID principles.
Single Responsibility:
- You are almost always at least bending the single responsibility principle with an extension method because you are tacking on to something that is already a class (that you either don't have control over or are too afraid to touch).
Open/Close Principle:
- Extension methods cannot be overridden, which means your method may not be adequately "open for extension".
Liskov substitution principle:
- If you have any sort of inheritance structure you will not be able to use the extension methods on the sub types.
Interface segregation principle:
- Although you can "extend" an interface, you have to provide a concrete implementation for that extension. So you can not program towards an interface >that can be implemented differently in a different context (eg Unit Test)
Dependency inversion principle:
- If your code has any dependencies, how are you going to expose those dependencies for factories and unit tests (dependency inversion principle)?
Finally, extension methods are just static methods wearing a new dress. So all of the difficulties with static methods (such as thread safety, garbage collection, etc) come along with extension methods when you implement them.
So, I would think long and hard about writing a method as an extension and reconsider using a factory and a basic helper class instead.
If you do write an extension method, please make it very simple. Try to avoid having any dependencies (or pass all of your dependencies in as parameters). And be careful for how you manage memory and lock resources in a multi-threaded environment.

What are extension methods?
Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.
How to use extension methods?
An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
Important points for the use of extension methods:
1.An extension method must be defined in a top-level static class.
2.An extension method with the same name and signature as an instance method will not be called.
3.Extension methods cannot be used to override existing methods.
4.The concept of extension methods cannot be applied to fields, properties or events.
5.Overuse of extension methods is not a good style of programming.

Use inheritance when "Is-A" relationship makes sense. Inheritance create unwanted dependencies between the classes.
I use extension method when I feel "what good it would have been if XYZ class had ABC method".
I remember the best exammple when I used extension method when I needed to break collection into chunks.
Here is the details.
https://www.codingcrest.com/extension-method-in-c/

Related

Extension method - having to use this keyword?

I have added an extension method to the ASP.NET System.Web.UI.Page.
Every page in my application inherits from this class.
I cannot just access the extension method, however. I must type this.MyMethod(); instead of just being able to use MyMethod(). I thought that methods/attributes of this were inherently in the default scope. What am I not understanding? Or is this a nuance of extension methods?
I thought that methods/attributes of
this were inherently in the default
scope.
They are. But extension methods are not methods of this in the default scope; they are static methods accessible via syntactic sugar provided as a courtesy by the compiler.
I believe you already know this, but just to clarify: if ExtensionMethod is an extension method of the class whose scope you're currently in, typing this:
this.ExtensionMethod();
...is the same as:
SomeStaticClass.ExtensionMethod(this);
this needs to be passed as a parameter to ExtensionMethod. The first way above, the compiler simply does this for you.
Naturally, they could have implemented things differently so that the compiler "brings in" extension methods as well as class members into the default scope; they just simply chose not to. Personally, I like that; but I guess it's a subjective matter. Anyway, if you dislike having to type this, it's only a small annoyance, right?
is this a nuance of extension methods?
Yes, it is. (As others have explained.)
If you want to use the method without any qualification, then you could just make a class that inherits from Page and includes your method (minus the first paramater, of course). Then make each page in your application inherit from your new custom page.
In order to use extension method you should declare:
using Namespace.Where.Extension.Method.Is.Located
And don't forget that class that holds extension method should be static.

Can't specify static methods as part of an Interface?

I have a set of objects that I want to conform to an interface, say ISpecialObject.
However a part of my implementation I want to encapsulate the instantiation trigger of these specialobjects within the implementation of each ISpecialObject.
So say for instance I have as list of class types that implement ISpecialObject, I then want to go through each one and call a static method like CanCreate(some data) which tells me whether or not to create an instance of one of these.
However, .net doesn't seem to let me specify this static CanCreate as part of the ISpecialObject interface.
Can anyone suggest a way to get around this, or alternatively a better approach to solving the problem of encapsulation of the instantiation of these objects? I may just be thinking about this all wrong.
Thanks.
Edit: I may have phrased some parts of this poorly. I don't want to provide the implementation in the interface, but rather specify that there will be one, and that it will be static. Essentially I want the objects to be self defining by allowing a higher level object to query when to create them at runtime.
From what I understand, your main issue is the instantiation of a set of objects that conform to the same interface. If that is so, you may want to look at the Factory Design Pattern which is the standard way to encapsulate such logic.
.NET does not allow static method declarations on interfaces. They don't really make sense since interfaces are all about the contract and avoid implementation entirely. Static methods are specifically about implementation. Additionally, interface methods are virtual function calls depending on the type of the instance, whereas static methods are independent of an instance or even a class (they could be put on any concrete type).
If you have many implementations of ISpecialObject, you could use a factory pattern. In order to do this, you would define define an interface called ISpecialObjectFactory alongside ISpecialObject:
class ISpecialObjectFactory
{
ISpecialObject CreateInstance(...);
bool CanCreate(...);
}
Each class that implements ISpecialObject should have a corresponding ISpecialObjectFactory (e.g. UserObject would have also have a UserObjectFactory). This would require a bit more code, but it's a common pattern and I believe it solves your problem.
I dont see the issue. The typename is just a prefix when dealing with static methods. It will make no difference what so ever if the static method lives somewhere else.
That said, look at extension methods, which may do want you really want it to :)
Edit: Another option might be using attributes.
We just discussed something very similiar to this on another thread. Extension methods are definitely a way to solve this problem. They can provide an implementation for an interface, and the methods can be treated as static or used as a method on an instance of an object which is being extended.
It is not exactly a duplicate in the way that you've phrased the question, but it is duplicate in nature so check out the link below.
StackOverflow - subclass-needs-to-implement-interface-property-as-static
Maybe you can use an abstract class as super class for your purpose. So the static methods go in the abstract class and all derived classes have that as well. However, I agree to the the posts above that may be using the factory pattern is a better approach here.

Prefer extension methods for encapsulation and reusability?

edit4: wikified, since this seems to have morphed more into a discussion than a specific question.
In C++ programming, it's generally considered good practice to "prefer non-member non-friend functions" instead of instance methods. This has been recommended by Scott Meyers in this classic Dr. Dobbs article, and repeated by Herb Sutter and Andrei Alexandrescu in C++ Coding Standards (item 44); the general argument being that if a function can do its job solely by relying on the public interface exposed by the class, it actually increases encapsulation to have it be external. While this confuses the "packaging" of the class to some extent, the benefits are generally considered worth it.
Now, ever since I've started programming in C#, I've had a feeling that here is the ultimate expression of the concept that they're trying to achieve with "non-member, non-friend functions that are part of a class interface". C# adds two crucial components to the mix - the first being interfaces, and the second extension methods:
Interfaces allow a class to formally specify their public contract, the methods and properties that they're exposing to the world.
Any other class can choose to implement the same interface and fulfill that same contract.
Extension methods can be defined on an interface, providing any functionality that can be implemented via the interface to all implementers automatically.
And best of all, because of the "instance syntax" sugar and IDE support, they can be called the same way as any other instance method, eliminating the cognitive overhead!
So you get the encapsulation benefits of "non-member, non-friend" functions with the convenience of members. Seems like the best of both worlds to me; the .NET library itself providing a shining example in LINQ. However, everywhere I look I see people warning against extension method overuse; even the MSDN page itself states:
In general, we recommend that you implement extension methods sparingly and only when you have to.
(edit: Even in the current .NET library, I can see places where it would've been useful to have extensions instead of instance methods - for example, all of the utility functions of List<T> (Sort, BinarySearch, FindIndex, etc.) would be incredibly useful if they were lifted up to IList<T> - getting free bonus functionality like that adds a lot more benefit to implementing the interface.)
So what's the verdict? Are extension methods the acme of encapsulation and code reuse, or am I just deluding myself?
(edit2: In response to Tomas - while C# did start out with Java's (overly, imo) OO mentality, it seems to be embracing more multi-paradigm programming with every new release; the main thrust of this question is whether using extension methods to drive a style change (towards more generic / functional C#) is useful or worthwhile..)
edit3: overridable extension methods
The only real problem identified so far with this approach, is that you can't specialize extension methods if you need to. I've been thinking about the issue, and I think I've come up with a solution.
Suppose I have an interface MyInterface, which I want to extend -
I define my extension methods in a MyExtension static class, and pair it with another interface, call it MyExtensionOverrider. MyExtension methods are defined according to this pattern:
public static int MyMethod(this MyInterface obj, int arg, bool attemptCast=true)
{
if (attemptCast && obj is MyExtensionOverrider)
{
return ((MyExtensionOverrider)obj).MyMethod(arg);
}
// regular implementation here
}
The override interface mirrors all of the methods defined in MyExtension, except without the this or attemptCast parameters:
public interface MyExtensionOverrider
{
int MyMethod(int arg);
string MyOtherMethod();
}
Now, any class can implement the interface and get the default extension functionality:
public class MyClass : MyInterface { ... }
Anyone that wants to override it with specific implementations can additionally implement the override interface:
public class MySpecializedClass : MyInterface, MyExtensionOverrider
{
public int MyMethod(int arg)
{
//specialized implementation for one method
}
public string MyOtherMethod()
{ // fallback to default for others
MyExtension.MyOtherMethod(this, attemptCast: false);
}
}
And there we go: extension methods provided on an interface, with the option of complete extensibility if needed. Fully general too, the interface itself doesn't need to know about the extension / override, and multiple extension / override pairs can be implemented without interfering with each other.
I can see three problems with this approach -
It's a little bit fragile - the extension methods and override interface have to be kept synchronized manually.
It's a little bit ugly - implementing the override interface involves boilerplate for every function you don't want to specialize.
It's a little bit slow - there's an extra bool comparison and cast attempt added to the mainline of every method.
Still, all those notwithstanding, I think this is the best we can get until there's language support for interface functions. Thoughts?
I think that C# follows slightly different logic - just like in Java, the axiom in C# is that everything is an object and all functionality should be encapsulated in the class (as methods). C# isn't as strict - there are value types that aren't really object and there are static members, which also don't belong to any object.
Extension methods add one capability that wasn't possible before - you can add members to interfaces (implemented in terms of the core members of the interface). This is great and very useful, but I think it should be used only when adding member to an interface is what you need (just like the use in LINQ).
One possible problem with prefering extension methods over instance methods is that you may later realize that you actually need to use some private state in the method - then you would have to change extension method into an instance method (which breaks binary compatibility) or expose some private information...
It would be definitely usable to distinguish between members that rely on private state directly and "derived" members that are implemented in terms of public operations, but I don't think that extension methods are that great for this. Perhaps it would be possible to mark such methods with some attribute (e.g. UsesOnlyPublic) and write some FxCop rule to make sure that the method doesn't violate the policy...
I generally like extension methods, particularly on interfaces, but I have two issues with them:
First, if an implementation has a more efficient way of achieving the extension method's purpose, there's no general way of expressing that. For example, Enumerable.Count() explicitly knows about ICollection/ICollection<T> and special-cases it. An alternative for this would be if interfaces could actually contain implementations directly, referencing only other interface methods and not declaring fields. The methods could then be overridden in appropriate implementations. This does mean you need to own the interface, of course... but in some cases it would be cleaner than current extension methods. (By avoiding the ability to introduce fields, I believe you get round some implementation problems which multiple inheritance of classes would introduce.)
Second, I don't like the way extension methods are discovered. There's no way to say, "I want the extension methods from class X" without also dragging in the extension methods from other classes in the same namespace. I would like you to be able to write:
using static System.Linq.Enumerable;
to pick up only those extension methods.
(Incidentally, I'll be talking more about both of these points at NDC 2010 on Thursday. Hopefully the talk will be recorded.)
The ability to specify general algorithms which only rely on the public interface is nice. The ability to call those algorithms on the type providing the interface is nice. The current mechanism just has a few sharp corners.
Incidentally, it might be quite nice to be able to write methods within a type but say, "Limit me to only using the public API."
Extension methods do seem to directly address the encapsulation principle that you cite. But I do see danger in their overuse. Without this language feature, you have basically two options for implementing your "non-member non-friend" functions that complement a given interface: static utility functions or a wrapper/proxy class.
I think the problem with the extension method approach is that it's basically a convenient syntactic construct around static utility functions. It just provides you with method call semantics for a static utility function.
But in the absence of extension methods I think most would agree that wrapper/proxy classes are a better way to implement your "non-member non-friend" functions. I think that this really just comes down to the organic growth of your codebase in an object-oriented way. The class that you make today as a simple wrapper/proxy may grow into a first class component in your system tomorrow. It's a real class, so it can have members of its own and potentially grow in scope along with your expanding use cases.
So I think extension methods have the danger of encouraging the proliferation of what are basically static utility functions at the expense of classes and objects, which are the constructs that you most want to cultivate in your codebase.

What is an Extension Class?

My teacher asked us to investigate what an Extension Class was but I can't seem to find anything on MSDN or Google. Any help?
There's no such thing as "extension class" in formal C# terminology. It might mean a class defining extension methods (which is not anything special, it's just a simple static class.)
Your teacher may also be talking about partial classes...
Technically an "extension class" is not anything. In the vernacular it could be used by someone to refer to a class that is designed to store extension methods. Extension methods are methods used to look like instance methods of a class, but which are truly static methods in a static class that are provided to enhance and encapsulate certain functionality. They are especially useful when you are trying to extend certain functionality on a type that you cannot modify directly and add a method to. Additionally, they are often used with generic types (especially within the .net 3.5 framework) to extend functionality using the methods provided by a specific interface.
A class that has extension methods.
Extension methods enable you to "add"
methods to existing types without
creating a new derived type,
recompiling, or otherwise modifying
the original type. Extension methods
are a special kind of static method,
but they are called as if they were
instance methods on the extended type.
For client code written in C# and
Visual Basic, there is no apparent
difference between calling an
extension method and the methods that
are actually defined in a type.
An Extension class in C# could simply be a child class( inheriting and adding more functionality to the base type or interface) or a static class.
I dont know extension class is there .But extension method is there .
Try this
Extension Method
I know this question is a little bit older but one thing that came to my mind when I read this question is the refactoring book by Martin fowler. In Chapter 7 Moving Features Between Objects, he describes a refactoring called Introduce Local Extension . There he talks about creation an extension class which is nothing more or less than a subclass or a wrapper around an object. The purpose of this extension class is to extend the functionality of an existing class like Date (The Java class Date not the DateTime class of .Net which is in fact sealed).
Some of the other answers here refered to the extension Method which seems to be another way of using the refactoring Introduce foreign Method. I am not sure about this, so I maybe mistaken here.
I think the book was written in 1999 with most examples in Java so maybe this doesn't relate so much to .Net but I guess the concept is universal.
The closest thing to an Extension Class that I can come up with is for example Microsoft's ExceptionExtensions class.
https://learn.microsoft.com/en-us/previous-versions/msp-n-p/ff654014(v=pandp.10)
If you create your own method in a class with that name, it becomes accessible from the Exception object.
public static class ExceptionExtensions
{
public static String myMethod(this Exception ex)
{
return ("Hi!");
}
}
Access it this way:
catch(Exception ex)
{
String message = ex.myMethod();
}

How to design a inherited collection

I'm writing a program in C# that has a custom collection. The custom collection performs some useful aggregate functions (AllSuccessful, %Successful, etc) over it's members which are of type ResultInfo. I have several classes that derive from ResultInfo (UploadResultInfo, XUploadResultInfo, and YUploadResultInfo), and would like to have additional collections that inherit from ResultInfoCollection that have additional aggregate functions. The only problem with doing this as specified is that it leaves a useless
public void Add(ResultInfo item)
{
}
on the collection. Clarification: This method takes an argument of type ResultInfo, but a ResultInfo added to an UploadResultInfoCollection will throw an error. Is there an elegant way of solving my problem? I've considered generics but I don't quite know how that would work.
To define a generic class that handles any child of ResultInfo you just define it like
public class MyCollection<T> : ICollection<T>
where T : ResultInfo
{
... the required methods ... just use "T" instead of "ResultInfo" ...
public void Add(T item) {}
}
Later on you can use it by
MyCollection<FooResultInfo> coll = new MyCollection<FooResultInfo>();
Just try using them, they are not too difficult and learning by doing is the best way ...
I'm not sure how you are left with a useless Add method.
If the collection populates itself, you can make the Add method private.
If you want your "inherited" additional collections to not expose the Add method, use composition instead of inheritance.
Consider whether your useful methods actually need to be instance methods.
Do they need to maintain state when other operations happen or are they all possible using the publically avaialable (or internaally available) API?
If so then simply make them static methods (extension methods is probably a good idea) and don't worry about inheritance. If the methods are meaningful on IEnumerable<T> then so much the better, by doing this you make your utility functions vastly more usable and thus useful.
Using the resulting package of functions simply requires importing the relevant namespace.
If all you're doing is providing some extra methods to an otherwise existing collection type, then consider simply defining extension methods for that type and using a normal generic collection.

Categories