Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I just read in msdn/books that extension methods are useful to add methods to existing classes if the existing class source code is not available , however I have noticed in some very good written open source codes that extension methods are still used along with with inheritance (abstract, interface) on classes that have source code written by the author himself/herself.
This is just general question , no source code here.
A common reason is dependency management: Let's say you have a fairly general class User and a not-so-general class GravatarImage. Now it might make sense to be able to call SomeUser.GravatarImage() instead of GravatarImage.ImageForUser(SomeUser). This is not only convenience; in a large project, it might be hard for other programmers to find out the 'right' way to do something. IntelliSense will help a lot here.
However, the User class is a "backend" class and should not need to know anything about images, views, gravatars or URLs, so you want to keep dependencies clean.
A similar argument applies to LINQ, which basically consists of extension methods. These extension methods, extend the collection interfaces, so you can create a lot of functionality with very small interfaces. Implementing a new kind of IEnumerable is very easy, yet you gain all the functionality that is provided by LINQ.
The IEnumerable interface, to stick to the example, doesn't allow much more than getting an enumerator. Instead of asking each implementor to provide a Count method, you can call the extension method which will accomplish the same.
It is noteworthy, however, that a method like IEnumerable.Count() can be very slow (it has to touch every element), whereas a direct implementation of the underlying class could be as simple as returning a simple int.
A lot of the answers already here are great: I love using extensions for optional behavior, and on interfaces. There are a couple of other good reasons.
Avoiding abstract method overloads. Consider the following interface:
public interface IUserService
{
User GetUser(int userId);
User GetUser(int userId, bool includeProfilePic);
}
We can see how it might be useful to optionally include the profile pic when getting a user from a IUserService. But, with both methods on the interface, they could be implemented in totally different ways (something this simple probably wouldn't, but I run across this problem a lot). Using extension methods, overloads cannot have divergent behavior:
public interface IUserService
{
User GetUser(int userId, bool includeProfilePic);
}
public static class UserServiceExtensions
{
public static User GetUser(this IUserService userService, int userId)
{
return userService.GetUser(userId, false);
}
}
Respect encapsulation. If you have a bit of additional functionality that you want to put on a class, but it does not need any access to internal members of the class to function, and holds no state, then using an extension method is desirable. The fewer things that know about a classes internal members and state the less coupling you will have, and the easier it will be to maintain code in the long run.
A downside: you can't Moq Extension Methods
A lot of times this doesn't matter. It means that, in order to mock out behavior behind an extension method, you usually need to know how the extension method works, and mock the virtual methods it calls. This couples your tests to an implementation of the extension method. This is just annoying if your extension method is simple and unlikely to ever change. This is pretty bad if your extension method encapsulates some complex set of calls. For that reason, I usually only use extension methods for relatively simple behaviors.
In C#, providing extension methods for an interface is usually an attempt at approximating* mixins.
A mixin can also be viewed as an interface with implemented methods.
Although C# does not support mixins, providing extension methods to an interface class that others can implement is a nice way of "bolting on" functionality.
Here's a real-world example of a simple interface with bolted on functionality delivered as a mixin:
public interface IRandomNumberGenerator
{
Int32 NextInt();
}
public static class RandomNumberGeneratorExtensions
{
public static Double NextDouble(this IRandomNumberGenerator instance)
{
return (Double)Int32.MaxValue / (Double)instance.NextInt();
}
}
// Now any class which implements IRandomNumberGenerator will get the NextDouble() method for free...
* The big difference between C#'s approximation of mixins and the real thing is that in supported languages mixins can contain private state, where as extension methods on interfaces in C# can obviously only access public state.
A good way to think of extension methods is like a plugin-type architecture - they give you the ability to include/exclude functionality for a particular type instance. To answer your question specifically:
Why to use extension methods if source code is available instead of inheritance
The simplest answer to that would be for optional functionality. The most common, and probably the most important, reason for using extension methods is being able to extend a particular type without changing any core functionality. Deriving new types for the sake of adding a couple of methods is overkill, even if you had control over the source it would make more sense to make the type partial instead. Extension methods tend to be used to solve problems for particular scenarios and don't really merit going into the core code base. However, should you find yourself using them all over the place then that's a good indicator that your probably not using them correctly.
For example, consider the following extension:
var epochTime = DateTime.UtcNow.ToEpochTime();
ToEpochTime would return me the date time as Unix Time. This would be useful as an alternative way of generating a timestamp or serializing the date. However, it's quite a specific function so it wouldn't make sense being part of DateTime but by making it an extension method it allows me to simply include this type of functionality if & when required.
There are a couple of disadvantages I can think of with subclassing as an alternative to extension methods:
It can be excessive if you only want to add a couple of lightweight methods.
It can create problems if you already have a complex inheritance structure (especially if your class already has subclasses), or intend to have one in future.
I often use extension methods for bridging boundaries between namespaces in a way that increases readability and maintains separation of concerns. For example myObject.GetDatabaseEntity() reads quite nicely, but the code for GetDatabaseEntity() should be in the database section of the code, not in my business logic. By putting this code in an extension method I can keep everything where it belongs without adding the complexity of subclassing.
Additionally, if myObject was instantiated in my business logic before being passed to the database code, then the business logic would need to include the database namespace. I prefer to have each module's responsibilities clearly demarcated, and would prefer my business logic to know as little as possible about the database.
There are also a couple of tricks that extension methods are useful for (some of which have been mentioned already in other answers):
They can be applied to interfaces (LINQ uses this a lot).
They can be applied to enums.
They can be used as event handlers if you create them with the correct signature. (Not that I'd recommend doing this as it can lead to confusion, but it can save you from storing references to objects that you would otherwise need to stick in a collection somewhere - watch out for leaks!)
This may be a somewhat specialized case, but I've found extension methods useful when providing "rules" of various types to existing classes.
Say you have a classe SomeDataContainer, with lots of members and data, and you want to export certain pieces of that data in some cases, and other pieces in other cases.
You could do something like this in SomeDataContainer:
if(ShouldIncludeDataXyz()){
exportXyz();
}
(...)
private bool ShouldIncludeDataXyz(){
// rules here
}
private void ExportXyz(){ (...) }
... but I've found that this sometimes gets messy, especially if you have lots of classes, and many rules, etc.
What I've done in some cases, is to place the rules in separate classes, with one "rule class" for each "data class", and create the rules as extention classes.
This just gives me a hierarchy of rules in one place, separated from the core data - a separation I find useful anyway.
The resulting code would still be similar to the above:
// This now calls an extention method, which can be found
// in eg. "SomeDataContainerRules.cs", along with other similar
// "rules"-classes:
if(this.ShouldIncludeDataXyz()){
exportXyz();
}
I'm working on a module that requires a strictly decoupled interface. Specifically, after instantiating the root object (a datasource), the user's only supposed to interact with the object model via interfaces. I have actual factory objects (I'm calling them providers) to supply instances that implement these interfaces, but that left the clumsiness of getting the providers. To do so, I've supplied a couple methods on the datasource:
public class MyDataSource
{
private Dictionary<Type, Type> providerInterfaceMapping = new Dictionary<Type, Type>()
{
{ typeof(IFooProvider), typeof(FooProvider) },
{ typeof(IBarProvider), typeof(BarProvider) },
// And so forth
};
public TProviderInterface GetProvider<TProviderInterface>()
{
try
{
Type impl = providerInterfaceMapping[typeof(TProviderInterface)];
var inst = Activator.CreateInstance(impl);
return (TProviderInterface)inst;
}
catch(KeyNotFoundException ex)
{
throw new NotSupportedException("The requested interface could not be provided.", ex);
}
}
}
I've modified some details on the fly to simplify (e.g., this code snippet doesn't include the parameters passed to the implementation instance that's created). Is this a good general approach for implementation of a factory method in C#?
You should rather take a step back and ask whether using a factory method at all is a good idea? In my opinion, it is not.
There are more than one issue with factory methods, and your example illustrates several:
You need to have a hard reference to the implementation (FooProvider in addition to IFooProvider), which is exactly the situation you are trying to avoid in the first place. Even if the rest of your code only consumes IFooProvider, your library is still tightly coupled to FooProvider. Some other developer may come by and start using FooProvider directly if he/she isn't aware of your factory method.
You only support implementations that have default constructors, since you are using Activator.CreateInstance. This prevents you from using nested dependencies.
Instead of trying to manually control dependencies, I would recommend that you take a look at Dependency Injection (DI). Whenever your code needs an IFooProvider, supply it with Constructor Injection.
Don't reinvent your own implementation of dependency injection, use an existing library like Spring.NET or the Microsoft Unity application block.
Injecting dependencies is a common programming problem that you shouldn't have to solve yourself. There are some nice lightweight libraries out there (I mentioned a couple above) that do the job well. They support both declarative and imperative models of defining dependencies and are quite good at what they do.
Technically this is fine, however most times when I see a factory it usually returns the same type interface, for instance something like IProvider rather than IFooProvider or IBarProvider which to me doesn't make sense. If you are going to have FooProvider and BarProvider then why have different interfaces for them. I would use one interface IProvider and have FooProvider and BarProvider implement that.
Regardless of the rightness or wrongness of using the factory method (as that is not what you asked about!), your implementation looks fine to me.
Something that may work for you better than hardcoding the type mapping is putting that info in a configuration file and loading it in your app.
For what it is worth I use this pattern all the time and have abstracted some of this sort of logic into a reusable assembly. It uses reflection, generics and attributes to locate and bind the concrete types at runtime. http://www.codeproject.com/KB/architecture/RuntimeTypeLoader.aspx
This helps to address Mark's concern because implementation types are not hardcoded, and further the implementation types are determined by the installation, not in project assembly references.
This question already has answers here:
When do you use reflection? Patterns/anti-patterns
(17 answers)
Closed 9 years ago.
So I tried searching SO hoping someone had a good explanation of this, with no luck.
I asked another friend of mine a different question (which I've now forgotten) and his answer was simply "reflection" before he signed off.
I am still very new to the C# world, having been an amateur VB.net programmer (also JavaScript, ActionScript, and C), and am trying as hard as I can to grasp these advanced concepts.
There's lots of philosophical answers -- "application looking at itself" -- but they don't provide any practical hints on what is actually going on or how it is used within that context.
So, what is reflection, why is it important, and why/how do I use it?
Reflection provides the ability to determine things and execute code at runtime.
You don't have to use it if you don't want to, but it is extremely handy for dynamic behavior.
For example:
a) You can use reflection to configure your application by loading an external configuration file and starting services based on it. Your application wont have to know in advance about the classes that implement those services, as long as they conform to a specific interface or API.
b) Using reflection you can generate classes and code on the fly, which simplifies certain programming tasks since the programmer does not have to explicitly create all the needed code.
c) Reflection is also invaluable for programs that work by examining code. An example of that would be an IDE or a UI designer.
d) Reflection helps you reduce boilerplate code.
e) Reflection is handy for defining mini Domain Specific Languages (DSL) in your code.
(my defintion)
Reflection is the ability to write static code that executes code at run-time, that is normally determined at compile time.
For instance, I could call a class method to draw by compiling in that command eg:
pen.DrawLine()
or With reflection, I can first see if my object has a method called "drawline" and if so, call it. (Note this isn't the actual C# Reflection syntax)
if(pen.Methods.Contains("DrawLine"))
{
pen.InvokeMethod("DrawLine"))
}
I'm no reflection master, but I used reflection for a plug-in architecture.
With reflection I can load a .NET assembly (a dll in this case) at run time, find out all the types that are in the .NET Assembly, see if any of those types implement a specific interface, and if so, instantiate the class, to which I invoke the interface methods.
I know that use-case is a bit technical, but essentially reflection allows me to load plug-ins dynamically (ie at run-time), and lets me make type-safe calls to it.
The most common use of reflection is an extension of what used to be called RTTI (run-time type information) and was primarily the domain of C++ programmers.
Reflection is a side-effect of the way .net is built and that Microsoft elected to expose the libraries they used to create Visual Studio and the .net run-time to developers outside of Microsoft.
Most of the reflection library focuses on type discovery and creation that can be invoked at run-time. This allows for some very powerful self-referential code. Take the following example at the heart of our configuration management system (some bits deleted for clarity):
public static IMyCompanySetting UnwrapSetting(XmlNode settingNode)
{
string typeName = settingNode.Attributes["type"].Value;
string typeAssembly;
if(settingNode.Attributes["assembly"] != null)
{
typeAssembly = settingNode.Attributes["assembly"].Value;
}
Type settingType = null;
Assembly settingAssembly = null;
try
{
// Create an object based on the type and assembly properties stored in the XML
try
{
settingAssembly = Assembly.Load(typeAssembly);
if (settingAssembly == null)
{
return null;
}
}
catch (Exception outerEx)
{
try
{
settingType = GetOrphanType(typeName);
}
catch (Exception innerEx)
{
throw new Exception("Failed to create object " + typeName + " :: " + innerEx.ToString(), outerEx);
}
}
// We will try in order:
// 1. Get the type from the named assembly.
// 2. Get the type using its fully-qualified name.
// 3. Do a deep search for the most basic name of the class.
if (settingType == null && settingAssembly != null) settingType = settingAssembly.GetType(typeName);
if (settingType == null) settingType = Type.GetType(typeName);
if (settingType == null) settingType = GetOrphanType(typeName);
if (settingType == null) throw new System.Exception(
String.Format("Unable to load definition for type {0} using loosest possible binding.", typeName));
}
catch (Exception ex)
{
throw new CometConfigurationException(
String.Format("Could not create object of type {0} from assembly {1}", typeName, typeAssembly), ex);
}
bool settingIsCreated = false;
IMyCompanySetting theSetting = null;
// If the class has a constructor that accepts a single parameter that is an XML node,
// call that constructor.
foreach (ConstructorInfo ctor in settingType.GetConstructors())
{
ParameterInfo[] parameters = ctor.GetParameters();
if (parameters.Length == 1)
{
if (parameters[0].ParameterType == typeof(XmlNode))
{
object[] theParams = { settingNode };
try
{
theSetting = (IMyCompanySetting)ctor.Invoke(theParams);
settingIsCreated = true;
}
catch (System.Exception ex)
{
// If there is a pre-existing constructor that accepts an XML node
// with a different schema from the one provided here, it will fail
// and we'll go to the default constructor.
UtilitiesAndConstants.ReportExceptionToCommonLog(ex);
settingIsCreated = false;
}
}
}
}
This code allows us to create a limitless number of classes that implement IMyCompanySetting and serialize and deserialize themselves using XML. Then, given a chunk of XML that is the output of object serialization, the system can turn it back into an object, even if the object itself is from a library that the serialization library doesn't have staticly linked.
There are 3 things that reflect does here that would be impossible without it:
Load an assembly at run-time based on its name.
Load an object from an assembly at run-time, based on its name.
Call an object constructor based on signature for an object of a class that is not known at compile time.
Say you have two alternate implementations of an interface. You want to allow the user to pick one or the other, via a simple text config file.
With reflection, you can simply read the name of the class whose implementation you want to use from the config file (as a string), and instantiate an instance of that class.
Reflection lets you dig into an assembly and use it, no matter that you don't have it referenced later.
Consider a plug-ins system, in which the host doesn't know about the plug-ins it will hold; with Reflection (and the correct architecture), you can construct a simple solution achieving this.
Consider another scenario in which you must to call the method on an object given a string, Reflection gives you the approach to achieve this as well.
There are many other usages but i hope these two, open your apetite to this excellent feature of CLR
It's sometimes useful to be able to read properties or invoke methods of a class without knowing what properties or methods a class has at design time. The way to accomplish this is with reflection. As demonstrated by the code below, you can get a list of all properties on a class and retrieve their values without knowing anything about it at compile time. Or you can get a method by name, even if you don't know the name of the method at compile time, and invoke it via reflection. This would allow you, for example, to create a scripting language that operates on objects defined in another user-supplied DLL. (Of course you can also enumerate all methods in a class or retrieve a specific property by name, but these cases are not demonstrated in the code below.)
class Program
{
static void Main(string[] args)
{
UserDefinedClass udc = new UserDefinedClass();
udc.UserProperty = "This is the property value";
ClassTracer ct = new ClassTracer(udc);
ct.TraceProperties();
ct.CallMethod("UserFunction", "parameter 1 value");
}
}
class ClassTracer
{
object target;
public ClassTracer(object target)
{
this.target = target;
}
public void TraceProperties()
{
// Get a list of all properties implemented by the class
System.Reflection.PropertyInfo[] pis = target.GetType().GetProperties();
foreach (System.Reflection.PropertyInfo pi in pis)
{
Console.WriteLine("{0}: {1}", pi.Name, pi.GetValue(target, null));
}
}
public void CallMethod(string MethodName, string arg1)
{
System.Reflection.MethodInfo mi = target.GetType().GetMethod(MethodName);
if (mi != null)
{
mi.Invoke(target, new object[] { arg1 });
}
}
}
class UserDefinedClass
{
private string userPropertyValue;
public string UserProperty
{
get
{
return userPropertyValue;
}
set
{
userPropertyValue = value;
}
}
public void UserFunction(string parameter)
{
Console.WriteLine("{0} - {1}", userPropertyValue, parameter);
}
}
Reflection is using the code to examine the code itself. For example, instead of calling foo.DoBar() you could call:
foo.GetType().GetMethod("DoBar").Invoke(foo,null);
That seems like a round-about method of getting to the same destination, but it can also be used to do some black magic that might break the rules, like calling private methods on framework classes, for example. It can also be used to actually generate code and output new binaries, and a whole slew of things that are extremely useful to a small group of people.
For more information, check out the MSDN section on Reflection.
There are many cases in which the application should not assume much about itself and should look at runtime to see what it actually is. This is where reflection comes into the show. For example, ASP.NET makes no assumption about the membership provider you use except that it inherits the appropriate class. It uses reflection to lookup the class at runtime and instantiate it. This gives out a great deal of extensibility due to decoupling and decreasing dependencies between classes.
This is, of course, only a single use case for reflection. There could be many other cases where it might be very useful.
Andrew Troelsen, author of Pro C# 2008 and the .NET 3.5 Platform, defines reflection this way:
In the .NET universe, reflection is the process of runtime type discovery.
I'm not sure I could give you an accurate explanation of what that means, but I can tell you how I've used it.
I can put a user-defined attribute on an assembly (dll). Using reflection at run-time, I can inspect all of the assemblies in a certain directory location to see if they have this attribute defined. This can clue my application on how to use the assembly, say as a plug-in.
I've also used reflection to load and save application settings.
For what it's worth, unless you're using reflection, I'm not sure what it has to do with your GUI throwing exceptions.
About the only thing I know about C#
reflection is that it is annoying as
hell because all my GUI apps like to
throw incredibly annoying, pointless
"Exception has been thrown by the
target of an invocation" exceptions at
Application.Run(new frmMain());,
instead of stopping where the real
problem happened (as shown in the
innerException).
Your statement makes me believe you have few if any try/catch blocks anywhere in your application such that every exception is percolating back to the top of the call stack. If you are using Visual Studio 2005/2008 in debug mode, go into the Debug menu and select the Exceptions... menu option. Inside the Exceptions dialog, check the checkboxes under the Thrown column. Now, when you run your application and an exception is thrown, the debugger will break where the exception is thrown.
Let's say you have some business entities which all come derive from a base class called Entity. Let's also say that you need/want all the derived classes to be cloneable. You can implement a method "Clone" (interface ICloneable) on the base class which would loop through all the properties of the current class (although it is implemented at the Entity class) and copy them to the cloned object. This is a case where Reflection can really help. Because you can't know the name and the count of the properties at the base class. And you don't want to implement the method in all derived classes. However you might want to make the method virtual.
Other people have answered for
what is reflection, why is it important
So I will be answering following questions only.
How do I use it?
Through following namespaces
System.Reflection
System.Reflection.Emit
Why do I use it?
To invoke/inspect assembly types, members, properties
When you look at a product like Reflector, being able to inspect code structure is more than practical enough.
If you run fast and furious, maybe you're inheriting from an object and need access to a private field. You don't have source, but thats ok you have Reflection. (hacky I know)
A more legitimate use I've seen is to use reflection in implementing C# generics where I want to do some operation on the generic type that isn't otherwise available. The only operations available on a generic type are those made available with a generic constraint (ie, if you constrain the generic type to implement IFoo, you can use IFoo methods on instances of that class). Some operations though just aren't available- for instance I was taking a generic class that was supposed to have a particular non-default constructor. I couldn't constrain the generic method to only accept generic type parameters with that constructor, but at least I could try and use that constructor when implementing the generic via reflection.
I use reflection sparingly but it occasionally comes in real handy.
I have used reflection to implement a custom data bindings system.
For example, with my bindings API I can write the following:
Binding b = new Binding(textBox, "Text", myObject, "Text", BindingMode.Bidirectional);
Any changes to the text in the textBox object are detected by the Binding object (which attaches to the TextChanged event) and passed into the myObject.Text property. Changes to myObject.Text are detected (by its TextChanged event) and passed into the textBox.Text member.
I implemented this system using reflection. The Binding constructor is declared as:
Binding(object, string, object, string, BindingMode)
The system therefore works with any object (with one important proviso).
I inspect the first object and find the member corresponding to the named member in the first string (textBox and "Text", ie. does textBox have a member called "Text"). Repeat with the second object and string.
Proviso: for objects to be used in this scheme they must implement the informal requirement that any bindable property must have a corresponding PropertyNameChanged event. Happily, pretty much all the .Net UI components follow this convention.
I then inspect the object for the requisite PropertyNameChanged events, add event handlers to them, and everything is set.
NB. I implemented this in .Net 1.0, so it predates Microsoft's bindings implementation - which I have not yet got round to investigating.
Practical Application
Use reflection for aligning Data with objects, as in a data mapping situation. For example, you can map a database column to an object's property. If you were to write an Object Relational Mapper, you would need some way to get from a configuration setting (i.e. DatabaseColumnName maps to Class.MemberName) to the objects to which it referring.
Reflection is so named because it allows ones code to take a look at itself just like looking in a mirror.
As previously mentioned reflection may be used to create new instances using a class name. Serialization is also powered by reflection. In this case the code examines all the serializable fields and serializes those recursively until the entire graph has been consumed and its byte form written.
Reflection allows one to escape static typing at compile time by discovering types, methods, fields etc at runtime. Many dynamic languages on the JVM (not sure about CLR but id imagine the same is true) use reflection to dispatch methods.
In terms of a practical use for reflection we have used it to allow our customers to provide their own localisation.
With our applications we provide a local resource database that the client can work through providing language translation for all strings, menu items, dialog controls...etc. With this client translated database in place we then use reflection on application launch and iterate through all our controls and replace default language strings with the client supplied translated strings.
There are many uses for reflection that have already been detailed here but another use might be to log the state of an object including its private members for use in debugging.
Can you post some sample code which shows how you are performing reflection? Do you have the PDB files in the same location as the assembly on which you are using the reflection API's?
If so, then in Visual studio go to the Debug menu -->Exceptions and check the check box "Common Language runtime thrown". Run your application in debug mode. Hopefully the debugger should break at the point in your reflected assembly at which the real exception is being thrown.
I've thought of this before and it came to mind again when reading this question.
Are there any plans for "extension properties" in a future version of C#?
It seems to me they might be pretty stright-forward to implement with a little more "compiler magic". For example, using get_ and set_ prefixes on extension method names would turn that method into an extension property:
public class Foo
{
public string Text { get; set; }
}
public static class FooExtensions
{
public static string get_Name(this Foo foo)
{
return foo.Text;
}
public static void set_Name(this Foo foo, string value)
{
foo.Text = value;
}
}
Are there any technical restrictions which would prevent this? Would this create too much stuff going on behind the scenes? Not important enough to be worth the effort?
The official site for feature requests is http://connect.microsoft.com/VisualStudio.
There has already been a request for extension properties here.
Microsoft's answer on 7/29/2008 included the following:
Extension properties are a common
request, and we actually got quite far
with a design for the next version of
the language, but ultimately had to
scrap it because of various
difficulties. It is still on our
radar.
Generally I think this would encourage poor practice.
Properties are supposed to represent some kind of state about the object in question, whereas methods should represent units of work. But many developers tend to put computationally intensive or relatively long-running code in the getters and setters where they would be much more appropriate as methods.
Extending an object is not the same as deriving from it. If you need to add properties, from a philosophical perspective you're talking about needing to add stateful information to the object. That should be done by deriving from the class.
Although I don't think what you're proposing is a good idea, you can get pretty much the same thing with the upcoming dynamic type in C# 4. Part of what is planned is to allow new properties and methods to be added at runtime to existing objects and types. One difference is that you won't have the compile-time checking of an extension property.
There might be something to be said about that kind of trick.
Just look at Attached properties in WPF. They do give tremendous power for declarative behavior attachment. But I'm not sure what that would look like outside of a declarative context...
I'm not sure how that would work. Extensions have to be static, so the property itself would have to static. The means whatever you use to back these properties would also be static. But expect your planned use for these expects them to be associated with the instances indicated by the this keyword rather than the type itself.
"Extension properties" are available today via inheritance. Adding such a beast would encourage poor oop practices and generaly be more trouble than its worth.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
A "non-believer" of C# was asking me what the purpose to extension methods was. I explained that you could then add new methods to objects that were already defined, especially when you don't own/control the source to the original object.
He brought up "Why not just add a method to your own class?" We've been going round and round (in a good way). My general response is that it is another tool in the toolbelt, and his response is it is a useless waste of a tool... but I thought I'd get a more "enlightened" answer.
What are some scenarios that you've used extension methods that you couldn't have (or shouldn't have) used a method added on to your own class?
The only advantage of extension methods is code readability. That's it.
Extension methods allow you to do this:
foo.bar();
instead of this:
Util.bar(foo);
Now there are a lot of things in C# that are like this. In other words there are many features in C# that seem trivial and don't have great benefit in and of themselves. However once you begin combining these features together you begin to see something just a bit bigger than the sum of its parts. LINQ benefits greatly from extension methods as LINQ queries would be almost unreadable without them. LINQ would be possible without extension methods, but not practical.
Extension methods are a lot like C#'s partial classes. By themselves they are not very helpful and seem trivial. But when you start working with a class that needs generated code, partial classes start to make a lot more sense.
I think extension methods help a lot when writing code, if you add extension methods to basic types you'll get them quicky in the intellisense.
I have a format provider to format a file size. To use it I need to write:
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "{0:fs}", fileSize));
Creating an extension method I can write:
Console.WriteLine(fileSize.ToFileSize());
Cleaner and simpler.
Don't forget tooling! When you add an extension method M on type Foo, you get 'M' in Foo's intellisense list (assuming the extension class is in-scope). This make 'M' much easier to find than MyClass.M(Foo,...).
At the end of the day, it's just syntactic sugar for elsewhere-static-methods, but like buying a house: 'location, location, location!' If it hangs on the type, people will find it!
Two more benefits of extension methods that i have come across:
A fluent interface can be encapsulated in a static class of extension methods, thereby achieving a separation of concerns between the core class and it's fluent extensions; I've seen that achieve greater maintainability.
Extension methods can be hung off of interfaces, thereby allowing you to specify a contract (via an interface) and an associated series of interface-based behaviors (via extension methods), again offering a separation of concerns. An example are the Linq extension methods like Select(...), Where(...), etc. Hung off the IEnumerable<T> interface.
Some of the best uses I had for extension methods is the ability to:
Extend functionality on third party objects (whether commercial or internal to my company but managed by a separate group), which in many cases will be marked as sealed.
Create default functionality for interfaces without having to implement an abstract class
Take for example, IEnumerable<T>. While it is rich in extension methods, I found it annoying that it did not implement a generic ForEach method. So, I made my own:
public void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
{
foreach ( var o in enumerable )
{
action(o);
}
}
Voila, all my IEnumerable<T> objects regardless of implementing type, and whether or not I wrote it or someone else did now have a ForEach method by adding an appropriate "using" statement in my code.
One of the great reasons for using extension methods is LINQ. Without extension methods a lot of what you can do in LINQ would be very hard. The Where(), Contains(), Select extension methods means a lot more functionality is added to existing types without changing their structure.
There are plenty of answers about the advantages of extensions methods; how about one addressing the disadvantages?
The biggest disadvantage is that there's no compiler error or warning if you have a regular method and an extension method with the same signature in the same context.
Suppose you create an extension method applying to a particular class. Then later someone creates a method with an identical signature on that class itself.
Your code will compile, and you may not even get a runtime error. But you're no longer running the same code as before.
Fluent Interfaces and Context Sensitivity as demonstrated by Greg Young on CodeBetter
I would like to support the other answers here that mention improved code readability as an important reason behind extension methods. I'll demonstrate this with two aspects of this: method chaining vs. nested method calls, and cluttering of a LINQ query with meaningless static class names.
Let's take this LINQ query as an example:
numbers.Where(x => x > 0).Select(x => -x)
Both Where and Select are extension methods, defined in the static class Enumerable. Thus, if extension methods didn't exist, and these were normal static methods, the last line of code would essentially have to look like this:
Enumerable.Select(Enumerable.Where(numbers, x => x > 0), x => -x)
See how much nastier that query just got.
Second, if you now wanted to introduce your own query operator, you would naturally have no way of defining it inside the Enumerable static class, like all the other standard query operators, because Enumerable is in the framework and you have no control over that class. Therefore, you'd have to define your own static class containing extension methods. You might then get queries such as this one:
Enumerable.Select(MyEnumerableExtensions.RemoveNegativeNumbers(numbers), x => -x)
// ^^^^^^^^^^^^^^^^^^^^^^
// different class name that has zero informational value
// and, as with 'Enumerable.xxxxxx', only obstructs the
// query's actual meaning.
My personal argument for Extension methods is, they fit very well into an OOP design:
consider the simple method
bool empty = String.IsNullOrEmpty (myString)
in comparison to
bool empty = myString.IsNullOrEmpty ();
There are heaps of great answers above about what extension methods let you do.
My short answer is - they nearly eliminate the need for factories.
I'll just point out that they are not a new concept and one of the biggest validations of them is that they are a killer feature in Objective-C (categories). They add so much flexibility to framework-based development that NeXT had NSA and Wall Street financial modelers as major users.
REALbasic also implements them as extends methods and they have been of similar use there simplifying development.
Its true that you can add your (extension) method directly into your class. But not all classes are written by you. Classes from the core library or third party libraries are often closed and it would be impossible to get the syntatic sugar without extension methods. But remember, extension methods are just like (static) standalone methods in eg. c++
Extension methods can also help keep your classes and class dependencies clean. For instance, you may need a Bar() method for the Foo class everywhere Foo is used. However, you may want a .ToXml() method in another assembly and only for that assembly. In that case, you can add the necessary System.Xml and/or System.Xml.Linq dependencies in that assembly and not in the original assembly.
Benefits: dependencies in your defining class assembly is reduced to only the bare necessities and other consuming assemblies will be prevented from using the ToXml() method. See this PDC presentation for further reference.
I agree that extension methods increases readability of code, but it's really nothing else than static helper methods.
IMO using extension methods for adding behaviour to your classes can be:
Confusing:
Programmers might believe that methods are a part of the extended type, thus not understanding why the methods are gone when the extension-namespace isn't imported.
An antipattern:
You decide to add behaviour to types in your framework using extension methods, then shipping them off to some person which into unit testing. Now he's stuck with a framework containing a bunch of methods he can't fake.
Extension methods are really the .NET incorporation of the "Introduce Foreign Method"refactor from Martin Fowler's Book (down to the method signature). They come with basically the same benefits and pitfalls. In the section on this refactor he says that they're a work-around for when you can't modify the class that should really own the method.
I mainly see extension methods as an admission that perhaps they shouldn't have disallowed free functions.
In the C++ community, it is often considered good OOP practice to prefer free nonmember functions over members, because these functions don't break encapsulation by gaining access to private members they don't need. Extension methods seem to be a roundabout way to achieve the same thing. That is, a cleaner syntax for static functions which don't have access to private members.
Extension methods are nothing more than syntactic sugar, but I don't see any harm in using them.
Intellisense on the object itself instead of having to call some ugly utility function
For conversion functions, can change "XToY(X x)" to "ToY(this X x)" which results in pretty x.ToY() instead of ugly XToY(x).
Extend classes you have no control over
Extend functionality of classes when its undesirable to add methods to the classes themselves. For example, you can keep business objects simple and logic-free, and add specific business logic with ugly dependencies in extension methods
I use them to reuse my object model classes. I have a bunch of classes that represent objects that I have in a database. These classes are used in the client side only to display the objects so the basic usage is accessing properties.
public class Stock {
public Code { get; private set; }
public Name { get; private set; }
}
Because of that usage pattern I don't want to have business logic methods in these classes, so I make every business logic to be an extension method.
public static class StockExtender {
public static List <Quote> GetQuotesByDate(this Stock s, DateTime date)
{...}
}
This way I can use the same classes for business logic processing and for user interface displaying without overloading the client side with unnecessary code.
One interesting thing about this solution it's that my object model classes are dynamic generated using Mono.Cecil, so it would be very difficult to add business logic methods even if I wanted. I have a compiler that reads XML definition files and generate these stubs classes representing some object I have in the database. The only approach in this case is to extend them.
It allows C# to better support dynamic languages, LINQ and a dozen other things. Check out Scott Guthrie's article.
In my last project, I used extension method to attach Validate() methods to business objects. I justified this because the business objects where serializable data transfer objects and will be used in diffrent domains as they where general ecommerce entities such as product, customer, merchant etc. Well in diffrent domains the business rules may be diffrent as well so I encapsulated my late bound validation logic in a Validate method attahced to the base class of my data transfer objects. Hope this makes sense :)
One case where extension methods were quite useful was in a client-application that uses ASMX web services. Due to the serialization, the return types of web methods do not contain any methods (only the public properties of these types are available on the client).
Extension methods allowed use to add functionality (on the client-side) to the types returned by web methods without having to create yet another object model or numerous wrapper classes on the client-side.
Extension methods can be used to create a kind of mixin in C#.
This, in turn, provides better separation of concerns for orthogonal concepts. Take a look at this answer as an example.
This can also be used to enable roles in C#, a concept central to the DCI architecture.
Also remember that extension methods were added as a way to help Linq query to be more readable, when used in their C# style.
These 2 affectations are absolutely equivalent, yet the first is far more readable (and the gap in readibility would of course increase with more methods chained).
int n1 = new List<int> {1,2,3}.Where(i => i % 2 != 0).Last();
int n2 = Enumerable.Last(Enumerable.Where(new List<int> {1,2,3}, i => i % 2 != 0));
Note that the fully qualified syntax should even be :
int n1 = new List<int> {1,2,3}.Where<int>(i => i % 2 != 0).Last<int>();
int n2 = Enumerable.Last<int>(Enumerable.Where<int>(new List<int> {1,2,3}, i => i % 2 != 0));
By chance, the type parameters of Where and Last don't need to be explicitely mentioned as they can be infered thanks to the presence of the first parameter of these two methods (the parameter which is introduced by the keyword this and make them extension methods).
This point is obviously an advantage (among others) of the extension methods, and you can take benefit from it in every similar scenario where method chaining is involved.
Especially, it is the more elegant and convincing way I found to have a base class method invokable by any subclass and returning a strongly typed reference to this subclass (with the subclass type).
Example (ok, this scenario is totally cheesy) : after a good night, an animal opens the eyes then gives a cry; every animal opens the eyes the same way, whereas a dog barks and a duck kwaks.
public abstract class Animal
{
//some code common to all animals
}
public static class AnimalExtension
{
public static TAnimal OpenTheEyes<TAnimal>(this TAnimal animal) where TAnimal : Animal
{
//Some code to flutter one's eyelashes and then open wide
return animal; //returning a self reference to allow method chaining
}
}
public class Dog : Animal
{
public void Bark() { /* ... */ }
}
public class Duck : Animal
{
public void Kwak() { /* ... */ }
}
class Program
{
static void Main(string[] args)
{
Dog Goofy = new Dog();
Duck Donald = new Duck();
Goofy.OpenTheEyes().Bark(); //*1
Donald.OpenTheEyes().Kwak(); //*2
}
}
Conceptually OpenTheEyes should be an Animal method, but it would then return an instance of the abstract class Animal, which doesn't know specific subclass methods like Bark or Duck or whatever. The 2 lines commented as *1 and *2 would then raise a compile error.
But thanks to the extension methods, we can have kind of a "base method which knows the subclass type on which it is called".
Note that a simple generic method could have done the job, but in a far more awkward way :
public abstract class Animal
{
//some code common to all animals
public TAnimal OpenTheEyes<TAnimal>() where TAnimal : Animal
{
//Some code to flutter one's eyelashes and then open wide
return (TAnimal)this; //returning a self reference to allow method chaining
}
}
This time, no parameter and thus no possible return type inference. The call can be nothing other than :
Goofy.OpenTheEyes<Dog>().Bark();
Donald.OpenTheEyes<Duck>().Kwak();
... which can weigh the code a lot if more chaining is involved (especially knowing that the type parameter will always be <Dog> on Goofy's line and <Duck> on Donald's one...)
I have only one word to tell about it: MAINTAINABILITY this is the key for extension methods use
I think extension methods help to write code that is clearer.
Instead of putting a new method inside your class, as your friend suggested, you put it in the ExtensionMethods namespace. In this way you maintain a logical sense of order to your class. Methods that don't really directly deal with your class won't be cluttering it up.
I feel extension methods make your code clearer and more appropriately organized.
It allows your editor/IDE do auto-complete suggestion smart.
I love them for building html.
Frequently there are sections that are used repeatedly, or generated recursively where a function is useful but would otherwise break the flow of the program.
HTML_Out.Append("<ul>");
foreach (var i in items)
if (i.Description != "")
{
HTML_Out.Append("<li>")
.AppendAnchor(new string[]{ urlRoot, i.Description_Norm }, i.Description)
.Append("<div>")
.AppendImage(iconDir, i.Icon, i.Description)
.Append(i.Categories.ToHTML(i.Description_Norm, urlRoot)).Append("</div></li>");
}
return HTML_Out.Append("</ul>").ToString();
There are also situations where an object needs custom logic to be prepared for HTML output- extension methods let you add this functionality without mixing presentation and logic within the class.
I've found extension methods are useful to match nested generic arguments.
That sounds a bit wierd - but say we have a generic class MyGenericClass<TList>, and we know that TList itself is generic (e.g. a List<T>), I don't think that there's a way to dig out that nested 'T' from the List without either extension methods or static helper methods. If we only have static helper methods at our disposal, it's (a) ugly, and (b) will force us to move functionality that belongs in the class to an external location.
e.g. to retrieve the types in a tuple and convert them into a method signature we can use extension methods:
public class Tuple { }
public class Tuple<T0> : Tuple { }
public class Tuple<T0, T1> : Tuple<T0> { }
public class Caller<TTuple> where TTuple : Tuple { /* ... */ }
public static class CallerExtensions
{
public static void Call<T0>(this Caller<Tuple<T0>> caller, T0 p0) { /* ... */ }
public static void Call<T0, T1>(this Caller<Tuple<T0, T1>> caller, T0 p0, T1 p1) { /* ... */ }
}
new Caller<Tuple<int>>().Call(10);
new Caller<Tuple<string, int>>().Call("Hello", 10);
That said, I'm not sure where the dividing line should be - when should a method be an extension method, and when should it be a static helper method? Any thoughts?
I have input zones on my screen, and all must implement a standard behavior whatever their exact types are (textboxes, checkboxes, etc.). They cannot inherit a common base class as each type of input zone already derives from a specific class (TextInputBox, etc.)
Maybe by going up in the inheritance hierachy I could find a common ancestor like say WebControl, but I didn't develop the framework class WebControl and it doesn't expose what I need.
With the extension method, I can :
1) extend the WebControl class, and then obtain my unified standard behavior on all my input classes
2) alternatively make all my classes derive from an interface, say IInputZone, and extend this interface with methods. I will now be able to call extensions methods related to the interface on all my input zones. I thus achieved a kind of multiple inheritance since my input zones already derived from multiple base classes.
There are so many great examples of extension methods..especially on IEnumerables as posted above.
e.g. if I have an IEnumerable<myObject> I can create and extension method for IEnumerable<myObject>
mylist List<myObject>;
...create the list
mylist.DisplayInMyWay();
Without Extension Methods would have to call:
myDisplayMethod(myOldArray); // can create more nexted brackets.
another great example is creating a Circular Linked List in a flash!
I can' take credit for it!
circlular linked list using extension Methods
Now combine these and using extension Methods code reads as follows.
myNode.NextOrFirst().DisplayInMyWay();
rather than
DisplayInMyWay(NextOrFirst(myNode)).
using Extension Methods It is neater and easier to read and more object orientated.
also very close to :
myNode.Next.DoSomething()
Show that to your collegue! :)