What is an Extension Class? - c#

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();
}

Related

how to hide method overloads from intellisense and main class code file when project is part of VS2013 solution?

I have too many method overloads for each method and I'm thinking how to make MyClass more easily understandable/usable to other developers. My ideas:
1.
make it partial class and new file name MyClassOldMethods.cs with all methods marked
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
this does not work, cause project is part of solution.
2.
Make old method overload as extension methods in other file in new static class. But I can't hide them from intellisense or can I?
Lots of existing code exist so the solution must be backward compatible. I have a feeling that this is wrong in a 1st place, but can it be done?
Edit:
SO wants me to explain that How to hide public methods from intellisense is not a duplicate. it does not answer the question. i read it before posting. The answers clearly state that EditorBrowsableState does not hide anything in same solution and it has nothing to do with partitioning obsolete but somewhere used overloads. I want to know is it wrong to move instance mthods to extension methods.
Extension methods will be hidden from Intellisense if they are in a separate namespace which is defined among the using namespaces. If you need an extension method you can always add using some.namespace.with.extensions and it will be available again. This approach should be used wisely and extension methods should be used where they are appropriate. ReSharper doesn't use this rule and shows all possible extension methods from referenced libraries.
If a class implements many interfaces and there is no need to show all implemented methods, you can use the explicit implementation, for example:
public class SomeClass : SomeInterface
{
void SomeInterface.SomeInterfaceMethod()
{
// ... some code ...
}
}
When you check all methods of the class, SomeInterfaceMethod will not be shown unless the class is cast to the SomeInterface type.

Why does C# allow multiple inheritance though interface extension methods but not classes? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I've checked through other questions and surprisingly this question doesn't seem to have been asked. With Extension methods, interfaces provide limited but true implementation multiple inheritance. This brings with it the Diamond problem, the same as with class based multiple inheritance. Why is this better or more acceptable than class based multiple inheritance that so many people seem to find so horrifying? It actually seems a much worse way of implementing multiple inheritance as extension methods can't go in the interface itself or even a class that implements the interface but can end up scattered over multiple static utility classes.
Eric Lippert in his blog (5 Oct 2009 9:29 AM) seemed open to the idea of extension properties and even mentions the possibility of extension events, extension operators, extension constructors (also known as "the factory pattern"). So implementation through interfaces could be further extended.
Edit: To clarify if a class inherits from two interfaces that both have an extension method of the same name and type parameters then it will produce a compile error if a method is called with out explicitly naming the interface. Having thought about this I was mistaken as this is not the Diamond problem. However thinking about this raises the question of what is so important about the Diamond problem as opposed to other ambiguities? Why is the Diamond problem such a difficulty, that it can it not be picked up with a simple compile error the same as when interface extension methods class clash and are not implicitly resolvable? Even within class based multiple inheritance it is possible to have member signature clashes that are not Diamond based.
With extension methods, interfaces provide limited but true implementation multiple inheritance.
This sentence is the basis for the entire question but I cannot make heads nor tails of it, so it will be difficult to answer the question.
First off, let's clearly define "inheritance". When we say that a type D inherits from a type B, what we mean is that every member of B is also a member of D†. That is all that we mean by "inheritance" in C#.
A class (or struct) inherits members from exactly one(††) base class. A class may implement any number of interfaces; this is quite different from base class inheritance. A class is not required to have the same set of members that an interface it implements has, because the class can use explicit interface implementation to provide an implementation without making a member of the class. The explicit interface implementation is only accessible via the interface, and cannot be accessed in any other way, so it would be strange to think of it as a "member" of the class that is "inherited" from the interface.
An interface "inherits" members from any number of other interfaces. And technically, this can be thought of as inheritance; members of the base interfaces are members of the derived interface. But I wish that we had not described it like that in the specification; I think it would have been more clear to say that interfaces do not inherit from base interfaces; rather, an interface can require the implementation of other interfaces as part of its contract.
Now that we've got that out of the way, what about extension methods? Extension methods are not any kind of inheritance; the type that is extended does not get any new members. Extension methods are rather just a way to more pleasantly write a call to a static method.
This brings with it the Diamond problem, the same as with class based multiple inheritance
It is unclear what "this" refers to in that sentence. Are you referring to (1) classes implementing multiple interfaces, (2) interfaces inheriting from multiple interfaces, or (3) something about extension methods, or (4) something else entirely? I do not understand what the diamond problem has to do with your question. Can you clarify it?
Why is this better or more acceptable than class based multiple inheritance that so many people seem to find so horrifying?
Why is what better?
I'm not understanding this question at all but it seems like there is some kind of useful question in here somewhere. Can you clarify the question? Preferably with some short, simple example code that demonstrates what you're talking about.
† Not every member. Constructors and destructors for example are members, but are not inheritable members. Private members are inherited but might not be accessible by name.
†† Except for object, which inherits from zero classes. Every other class inherits from exactly one class.
Any appearance of extension methods implementing multiple inheritance is wholly an illusion. They do not.
Extension methods are faily simple compiler tricks. They compile to plain old static methods that look and work just as they would with the this removed from the first parameter.
Consider:
myObj.Extension();
...
public static class MyExtension
{
public static void Extension(this MyObj myobj)
Calling the extension is equivalent to this:
MyExtension.Extension(myObj);
You can even call it like that in your code, of course.
The list of interfaces a C# class implements is flattened, so when a class implements an interface by virtue of inheriting it through multiple interfaces that it implements, the number of implementations the class needs to provide remains one.
For example, if a class implements two interfaces both of which inherit from IDisposable, that class still needs to implement Dispose() only once. This is in contrast to C++, where functions that are inherited from the same base class through multiple paths of non-virtual inheritance need to be overriden separately.
Extension methods are orthogonal to this issue, because the implementations they provide cannot be overriden. I wrote a blog post on extension methods and their role in sharing implementation "horizontally". I view them as a mechanism of providing functionality in a way entirely independent of the "vertical" implementation sharing that you get through class inheritance.
Extension methods are just glorified static methods that look like instance methods at call time (if the caller so chooses).
The situation you're describing cannot happen because the compiler will flag the call as ambiguous:
interface I1 { }
interface I2 { }
class C : I1, I2 { }
static class Ex1 {
public static void M(this I1 self) { }
}
static class Ex2 {
public static void M(this I2 self) { }
}
...
new C().M(); // ERROR: The call is ambiguous
Extension methods are only in effect if you import the namespace containing the static class with the extension method in the current context (via a using directive); or if your declarations live in the same namespace as them. So, even though you can create ambiguous declarations, if you add them to different namespaces, then the caller can disambiguate by only importing the desired namespace.
Also, to disambiguate, the caller can call the method as a normal static method:
Ex1.M(new C()); // not ambiguous anymore
Or you can cast to the appropriate interface:
((I1)new C()).M(); // not ambiguous anymore
So, it's not as if you're "inheriting" conflicting members that must be resolved at declaration time, you have both at your disposal, and you have to tell the compiler which one you want to use at call time.
Side note: I find this ability to extend interfaces an interesting way to create a form of mixin in C#. I've written about it before, e.g., here.

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.

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

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/

Categories