How do you manage the namespaces of your extension methods? - c#

Do you use a global, catchall namespace for all of your extension methods, or do you put the extension methods in the same namespace as the class(es) they extend?
Or do you use some other method, like an application or library-specific namespace?
I ask because I have a need to extend System.Security.Principal.IIdentity, and putting the extension method in the System.Security.Principal namespace seems to make sense, but I've never seen it done this way.

Put your extensions in the same namespace as the classes they extend. That way, when you use the class, the extensions are available to you.
If you are writing a extension for Uri, put the extension in System.
If it's a extension for DataSet, put it in System.Data.
Also, Microsoft says this about extension methods:
In general, we recommend that you
implement extension methods sparingly
and only when you have to. Whenever
possible, client code that must extend
an existing type should do so by
creating a new type derived from the
existing type.
For more info about extension methods, see the MSDN page about extension methods.

If they're extension methods used throughout the solution (e.g. over 60% of classes), I put them in the base namespace of the solution (since they'll be automatically imported being in a parent namespace, no importing the common stuff every time).
In this category, things like:
.IsNullOrEmpty(this string value) and .HasValue(this string value)
However, if they're very specific and rarely used, I put them in a BaseNamepace.Extensions namespace so they must be manually imported and don't show in intellisense cluttering things up everywhere.

I would recommend putting all your extension methods in a single namespace (incidentally this is also what Microsoft did with Linq by putting them in a single class 'Extensions' inside the 'System.Linq' namespace).
Since Visual Studio provides no clues as to how to locate an extension method that you want to use, it reduces confusion by only having to remember one namespace.

I upvoted the answer from user276695 which seemed the simplest solution. However I found an even better solution: no namespace at all. You can put a static class with extension methods at the very root of a file, without wrapping any namespace declaration around it. Then the extension methods will be available without having to import/using any namespace.†
I'm slightly worried about being down-voted from namespace nazis. But I feel compelled to champion a slightly unorthodox position. At least in my line of work (IT) I find that most of my custom tools are easier to maintain without namespaces, and placing everything in one giant anonymous namespace. I'm sure there are other programming universes where this would not work as well. But perferences & circumstances being different, I just wanted to point out that you can in fact declare classes without namespaces, even classes with extension methods - for those who also find a giant anonymous namespace better.
† You also get to save one level of indentation. :-) And even with 3 giant monitors I'm always looking for ways to save screen real-estate.

My practice is to put the extensions in a namespace that is different from yet clearly identifies the source namespace that I'm extending.
Generally, I create a namespace by prefixing my "company name" part of the namespace path in front of the namespace I'm extending, and then suffix it with ".Extensions"
For example, if I'm extending (for no good reason) ::System.Text.StringBuilder because it's sealed, then I will put my extensions in the namespace ::CodeCharm.System.Text.Extensions.
That's a rule of thumb for when I make extensions that I suspect I could re-use those extensions in other solutions.

If you put them in a higher namespace than your current, they will be visible automatically.
So if you have namespaces for projects like:
AdventureWorksInc.Web
AdventureWorksInc.Logic
AdventureWorksInc.DataAccess
Then declare your extension directly in:
namespace AdventureWorksInc
{
public static class HtmlHelpers
{
public static string AutoCloseHtmlTags(this string html)
{
//...
}
}
}
This extension method will show up whenever you are writing code in any sub name space of AdventureWorksInc without the need for a using statement.
However, the above extension demonstrates a possible downside. Due to the fact that it operates on strings, it will now show up as an extension method for all strings, including those that aren't really HTML. This is actually not an issue with namespace scoping, but simply a misuse of an extension method. This should be a regular static that requires a standard parameter so the call is explicit.
Generally well designed extension methods with appropriately typed parameters will not show up on types that it would never apply.

Related

Is it possible to have an extension class that works for other projects too?

In C# when we write an extension class it uses the this keyword to say that this extension method works on the objects of this namespace.
Now what if I want to write an extension class which works on other projects too? For example let's say my Controls project has this class and my Main project which has a reference to Controls porject want to call the extension methods, is it possible at all? Or I should rewrite the class in the Main project too?
Don't duplicate the methods; what you want is entirely possible. If your classes and their extensions are both declared in the Controls project you can access the extension methods in Main. You just have to remember to add a using statement to include the namespace where the extension methods are declared.
This is absolutely possible.
I guess you are missing the appropriate using statements as Visual Studio does not provide any guidence on that.
I tend to put the extensions into the same namespace as the type I am extending so if the types namespace is used the extension is also visible.
E.g. extensions for String are in the System namespace not MyApp.Something.Extensions.
This is especially usefull if other developers should use them as they may never know of their existence otherwise.

Is it acceptable to use extension methods on a class which you can modify

I've recently been toying with the idea of using extension methods to implement helper utilities on classes which I control (ie, are in the same program and I can modify). The rationale behind it is that many times, these helper utilities are used in very specific scenarios and don't require access to the classes internal values.
For instance, let's say I have a StackExchange class. It'd have methods like PostQuestion and Search and AnswerQuestion.
Now, what if I wanted to manually calculate my reputation to ensure that StackOverflow isn't cheating me. I'd implement something along the lines of:
int rep=0;
foreach(var post in StackExchangeInstance.MyPosts)
{
rep+=post.RepEarned;
}
I could add a method to the StackExchange class, but it doesn't require any internals, and it is only used from one or two other portions of the program.
Now imagine if instead you had 10 or 20 of these specific helper methods. Useful in a certain scenario for sure, but definitely not for the general case. My idea is changing something like
public static RepCalcHelpers
{
public static int CalcRep(StackExchange inst){ ... }
}
To something like
namespace Mynamespace.Extensions.RepCalculations
{
public static RepCalcExtensions
{
public static int CalcRep(this Stackexchange inst){...}
}
}
Note the namespace. I'd ideally use this to group extension methods within a certain scenario. For instance, "RepCalculations", "Statistics", etc.
I've tried searching for if this type of pattern is at all heard of, and haven't found any evidence of extension methods being used for anything but classes you can't modify.
What shortcomings are there with this "pattern"? Should I instead stick to inheritance or composition, or just a good ol' static helper class for this?
I would read the section of Framework Design Guidelines on Extension methods. Here is a post by one of the authors for the 2nd edition. The use case you are describing
(specialized helper methods) is cited by Phil Haack as a valid use for extension methods with the drawback that it requires extra knowledge of the API to find those "hidden" methods.
Not mentioned in that post but recommended in the book is that the extension methods go into a separate namespace from the extended class. Otherwise, they will always appear with intellisense and there is no way to turn them off.
I think I have seen this pattern somewhere else. It could quite confusing, but also quite powerful. That way you can provide a class in a library and a set of extension methods in separate namespace. Then whoever is using your library can choose to import namespace with your extension methods or provide their own extension methods.
A good candidate for this pattern would be if you have some extension methods used for unit testing only (e.g. to compare if two objects are equal in a sense you'd need for unit tests only).
You seem to be making the comparison that the extension method is equivalent to a public instance method. It's really not.
An extension method is just a public static utility method that happens to have a more convenient syntax for being called.
So first we have to ask ourselves, it it appropriate for this method to be an instance method of the class itself or is it more appropriate for it to be a static method of an external class. The fact that very few users of the class need this functionality because it's highly localized and not truly behavior that the class itself performs but rather behavior performed on the class by an external entity means that it's appropriate for it to be static. The primary drawback is that it's behavior that is potentially harder to find if someone has a User and wants to recalculate their rep. Now, in this particular case it's a bit on the fence, and you could go the other way, but I am leaning towards static method.
Now that we've decided it should be static it's an entirely separate question of whether or not it should be an extension method or not. This is much more subjective and goes into the personal preference realm. Are the methods likely to be chained? If so, extension methods chain much more nicely than nested calls to static methods. Is it likely to be used a lot in the files that do use it? If yes, extension methods are likely going to simplify the code a bit, if not, it doesn't really help as much, or even hurts. To the toy example I'd probably say that I personally wouldn't, but I wouldn't have any problem at all with someone who did (after all you can still use an extension method as if it's a regular public static method syntax wise). For a non-toy example, it's mostly a case-by-case decision. A key point is to be careful what classes you extend, and to ask yourself if a user is willing to clutter the Intellisense of a type just to call a methods slightly more conveniently (this again gets back to how much it's used per file it's used in).
It's also worth mentioning that there are a few edge cases where extension methods can be more powerful than instanced methods. In particular through utilizing type inference. With a regular instance method it's easy enough to accept a type or any sub-type of that type, but sometimes it's useful to return whatever the type is that was passed in instead of the parent type. This is used particularly in fluent APIs. This isn't a very common example though, and is only loosely related to your question, so I won't expand on that.
Extension methods could be very useful in cases where you class implements an interface and you want to avoid having to implement the same method on other "future" classes that implement the same interface. For example, StackExchange implements IStackExchange and ProgrammersExchange also implements IStackExchange. Your example extension method would be useful for implementing the CalcRep just once, and not having to re-implement it on both classes. This is exactly the reason for all the extension methods present in the static Enumerable class.
Other than this I dont see a compelling reason for using extension methods on a class you can already modify. If anything it has the disadvantage of being considered late in the overload resolution process.

Placing custom code in a System namespace

Are there any best-practices that state custom code shouldn't be placed in a System namespace? Should System and its children be reserved for Microsoft code?
I ask because I'm writing a class library that will be used across many projects and I'd like to keep things consistent by placing it in System.InteropServices (since it deals with P/Invoke).
It's not a good idea because it defeats one of the primary benefits of namespaces: preventing name clashes. What if a newer version of the framework introduced an identically named type in that namespace?
This is particularly bad for System namespaces since they are imported in many other pieces of code with using directives and introducing custom types in those namespaces pollutes the naming scope of other source files with unexpected identifiers.
To categorize your custom interop related types, you can create a new namespace like MyProduct.InteropServices.
If you place a new class in System.InteropServices, every file that has a using System.InteropServices; clause is forced to have your class in scope, which may confuse the programmer. Since the programmer cannot defend oneself against this, I'd consider this bad practise.
I disagree with everyone.
I think that in a limited subset of cases (mostly with extension methods) it is perfectly reasonable to place code in a system namespace.
Here is my side of the argument from an email thread we had debating Extension methods in the System namespace over at EPS:
Ok, so here's my side of the argument:
I really like to minimize code. That includes usings.
Yes, ReSharper picks up extension methods and adds the usings for you but some people don't have ReSharper, and besides, I prefer Coderush which as of yet does not actually (as far as I know) pick up extension namespaces.
There are at least two different types of extension methods; ones that are helper methods for our application - including domain and application-specific helpers, and ones that encapsulate features and syntax that we believe the language should have had to begin with.
A good example of the latter is the ability to do "a {0} {1}".Format("b", "c") or someListOfStrings.Join(", ") rather than having to do String.Join(someStringList.ToArray(), ", "). Other more debatable examples are IEnumerable<T>.ForEach and the IsNull() extension to take the place of the clumsy object.ReferenceEquals(null, someVar) syntax.
My argument is, that there is every reason to place this latter classification - your team broadly agrees should be in the language but aren't - in the appropriate namespace (System, System.IO, System.Linq, etc.). We want those functions to be available everywhere, just like we prefer the foreach and yield keywords to always be visible. If it is application-specific however it should go in its own namespace. 90% of the time application-specific helper extensions should likely not be extensions and not even be static. I exclude from this statement using extension methods to provide aliases for function names.
You can get in some trouble with this of course when calling into assemblies that contain system-wide extensions. Suppose that I was referencing the assembly containing my void IEnumerable<T>.ForEach method and wanted to create my own ruby-like R IEnumerable<T, R>.ForEach (which is actually just a Select, but nevermind that). This would be a problem! What I like to do to mitigate the issue is to define my extension classes as being internal so that they can be used only on my project. This solves the problem nicely.

Best practices: C# Extension methods namespace and promoting extension methods

I know there exists already a post, describing nearly the same, but I think mine is a bit different.
What I would like to know is how you organize your extension methods in terms of assigning the namespace. Currently - for the extension methods in our framework - I use the following namespace pattern
MyCompany.Web.Utils
and inside I have the extension method classes. This is fine for me with the disadvantage that the extenders are not immediately visible to our software developers. Consider the case where I have a StringExtender class which provides a quite handy extension method "In" that extends the String object. Having the extension method withing the above mentioned namespace, our programmers won't see the extension method unless they explicitly include its namespace. Instead, if I would put the extension method in the System namespace, everyone would immediately see it, but I've read that this is bad practice.
So my question is how you do promote your extension methods s.t. they are used by your developers.
We put them all in their own namespace Company.Common.Extensions. That way, if you have any of our extension methods, you have them all. Plus, at least at my shop, we don't have to worry about our developers not knowing about extension methods. I have the opposite worry, extension method overload! :)
The problem here is not the naming of the namespace, it's the lack of documentation and education of your developers.
Put them in whatever namespace makes sense, write a wiki article documenting all your extension methods, then send an email to your developers with a link to the wiki article.
This is not a namespace problem it is a communication problem.
If these methods are useful you need to communicate this to the developers and, conversely, act on the feedback from them (with appropriate levels of judgement).
Placing anything into the System namespace is a recipe for disaster and confusion later. The only times you ever want to do this is to 'back port' functionality into older frameworks and then you probably shouldn't do it yourself but should use something like LinqBridge to do it.
Be wary of the desire to throw all extensions into one namespace unless they really are widely useful together. Some developers may find the wood lost for the trees if they are bombarded with everything and the kitchen sink via intellisense.
Keeping the namespace the company name is sensible in general to avoid confusion.
#Juri- If you think about it this is the same problem as developers knowing that class X exists in the .NET framework. Communication is key that all team members use the right classes, be they extension methods or some other helper.
As JP has stated, I often see extension methods in some kind of subfolder called Extensions. Hopefully when you state you use my.company.web.utils the namespace is actually Pascal cased?
Even if you put them in a good place there is no 100% guarantee that other developers will use them.
Presuming you use Visual Studio, one way would be to create a custom Class template (or modify the default one) so that whenever a developer creates a new class file it automatically has a using statement with your namespace(s). See Customize Visual Studio 2005 Templates for Coding Productivity.
Yes,i think put the Extension methods in own company namespce is best practices. put it in System namespace is a lazy operation
I'm dumb, lazy and minimalistic, so I put them at the same namespace as the type they extend. In this way there is no need for extra using statements, documentation or emailing about them (Winston).
I like the way ReSharper solves this problem.
ReSharper discovers any available extension methods, even without the corresponding usings. In case the using is not present, Intellisense also shows the namespace where the extension resides, making clear where the extension comes from and indicating that selecting it will add the using. (Example below.)
Naturally, only namespaces reachable by the current project, i.e. directly or indirectly referenced, are included.
Here is an example of what Intellisense might show if there are two extension methods. The first one comes from a namespace that we have already included. The second comes from a namespace that we have not (yet) included.
AddMvc
AddEntityFrameworkSqlServer (Microsoft.Extensions.DependencyInjection)
We put everything into the same Namespace and Class, however we use partial classes to keep them organized.
For example:
ExtensionMethods-String.cs
ExtensionMethods-DataObject.cs
ExtensionMethods-Debug.cs
...etc all have partial classes...
You can achieve what you want by putting extension methods in the global namespace. That's what I do and they're then available without needing any using statements.

ASP.NET + C# Multi-Project Solution. Where should I put my global utility functions?

As the Title says, I've got a multi-project solution.
I've got a "core" project that is loaded with most of the other projects.
So my question is this, I have a few utility functions such as FormatPhoneNumber(..) that I would like to be able to access in the following manner from anywhere.
(in Project_B which depends on Core)
string str = FormatPhoneNumber(inputString);
At worst, I suppose I could live with a qualifier of some sort:
string str = util.FormatPhoneNumber(inputString);
The best way of doing this is to create a dll project (maybe called something like "CommonCode"?), that you can then reference this dll from all of your other projects and access the classes and methods therein.
You will have to have some sort of "qualifier" (as you call it) somewhere, but to reduce the impact use the using statement at the top of each file, e.g.
using util;
If you really must have such utility functions (you know, you shouldn't, but sometimes it's the best/easiest solution), I suggest having them either in the Core (assuming that every single project is dependent on the Core anyway), or in a separate utility assembly. If you don't want to have a separate assembly lying around, consider using ILMerge.
The qualifier should be no problem at all. I suggest not putting unrelated function into an Utils class, but rather use e.g. a Formatting class for all formatting functions. On the other hand, as s_ruchit in the meantime suggested, extension methods (e.g. for the string class) might come in handy as well.
(Did I mention that this §%$& MarkDown editor does not allow typing an [at] symbol on a German keyboard layout, because it instead creates a blockquote? Sigh.)
Try creating your own util library.
Create a Class Library project and put your util classes in there.
I myself try to adhere a naming convention like [companyName].Util.[subdomain]
Your example would probably fit in my [CompanyName].Utils.StringHelpers
You would then create a static class StringHelper with a static method FormatPhoneNumber.
You will see that these personal libraries quickly grow bigger. By grouping them you don't have to load all your code if you only need a subset of functions.
Use an extension method to make it easier to call the method without using the class name.
public static class Util {
public static string FormatPhoneNumber(this string input) {
:
}
}
The method will now appear on every string object. You do not need to know which class it comes from. However, if the extension class is declared in another namespace, you must still import the namespace.
string formattedString = inputString.FormatPhoneNumber();
If you are using C# 3.0, you can bind them all into one single static class use them as Extension Methods.
There are no global functions in .NET, so you will have to put your utility functions into a class. You can make the methods static, so you can call them without having to instantiate the utility class:
public class Utility
{
public static string FormatPhoneNumber(string input)
{
...
}
}
// usage:
string output = Utility.FormatPhoneNumber(input);
Put these methods into your core library or a separate utility library that can be used (referenced) by all other libraries and applications.
You need to put the functions in static classes. You cannot avoid the qualification (there are no global functions in C#):
<%= Formatters.PhoneNumber(rawData) %>
The utility functions should be grouped as per normal methods: similar methods go together, unrelated methods should go into different classes (event with static classes aim for low coupling and high cohesion).
The assembly each belongs in should be obvious: formatting functions only used by the presentation layer (ASP.NET project itself) belong there. Truly common functions could go into core.
If the function you are implementing can only be used in context of your application, i would recommend you to place it into the Core assembly (under a separate namespace like "Utils" for example) or a new DLL library of your application solution.
Only if the function can be used across multiple projects it makes sense to create a utility library. But always keep in mind that a utility library only make sense if it's maintained regularly.
If you want all code to access these methods then go with extension methods, otherwise I would go with Util class in core assembly.
FWIW, if you follow a more formalised namespace as boris sugguests (recommended to avoid conflicts) you can abbreviate with the using keyword:
using Util = [CompanyName].Utils.StringHelpers;
I tend to follow the DRY principle and create an alias as soon as I need it more than once.

Categories