Reputation: 61
I have an extension method for String that I want to be available on every code behind and class in my solution. The method is sitting in a particular namespace. I'd like everywhere to have access to that namespace without me having to include it in every class.
I've used the "namespaces" tag in the web config to successfully include it on every aspx page, but this does not make it accessible on code behind or elsewhere.
So, is there a similar way to include a namespace everywhere?
Upvotes: 1
Views: 1299
Reputation: 1118
You'll have put a using statement on every code file that intends to have access to the namespace, you can't "gloabally include."
Usually, it's good form to put your various utilities, static classes, and extension classes in a "Common" project that your other projects all have a dependency on. I've seen this pattern re-used a lot:
Using YourNameSpace.Common.Utilities;
Upvotes: 0
Reputation: 34846
No, you cannot.
The namespace
section of web.config
only provides those namespaces to the markup, but not code-behind.
<configuration>
<system.web>
<pages>
<namespaces>
<add namespace="System.Data" />
<add namespace="System.Text"/>
</namespaces>
</pages>
</system.web>
</configuration>
You must explicitly add namespaces via the using
statement in code-behind or add to one of the already included namespaces like System
, but that is not recommended.
Upvotes: 0
Reputation: 4315
Just put you extensions class into System namespace and it will be available for every String object.
namespace System
{
public static class Extensions
{
public static void M1(this string value)
{
...
}
}
}
Upvotes: 1
Reputation: 1038850
So, is there a similar way to include a namespace everywhere?
No, I am afraid that there isn't. If you place the extension method in some of the root namespaces then it will be in scope for the child namespaces. For example:
namespace Foo
{
public static class Extensions
{
public static void Go(this string value)
{
...
}
}
}
will be in scope inside all classes declared in Foo.*
namespaces. So you might put the extension method in a root namespace which has the same name as your project and then it will be available everywhere because all classes are automatically generated in child namespaces (unless you change that).
Upvotes: 1