c# add using declaration for namespace to all classes - c#

Is it possible to add a using declaration to a namespace globally?
For example, I want all of my classes under the "MyApp.Models" namespace to include the namespace System.Linq.Dynamic.
In asp.net you can do this for view by adding the namespace in the web.config. Is there a way to do this for class files as well?

No. It is not possible to add a global using declaration to a C# project. You must specify the complete set of using in each .cs file

It's not possible to do what you want with obvious functionality but you could create a template that you generate your classes from and do that by namespace, the templates could include the using and this would give you the desired effect.
You could do this with basic T4 templates or something like resharper also has this functionality.
However it is a bit pointless, lots of productivity tools will bring in the using statements you need given code you write, resharper and others do this, so it is not neccessary to have a template that does this as you may end up in each namespace not using the declaration then find yourself having to delete it !
Theres not really an issue with having using statements that are unused by the way its just messy.
Ooh just in case you aren't sure what t4 templating is here is a quick link

I don't believe this is possible out of the box, but you could certainly automate with a Visual Studio plugin or a plugin for a tool like Code Rush.

Related

Best way to get an accessable class in all of my projects

I need to declare an attribute for coverage exclusion in my code, the issue is that i have a project group and i wish to create it somewhere where i can access it from all projects when i need it, right now i have it outside of the namespaces so it would be easier to use, and its declared in each project like:
public class CoverageExcludeAttribute : Attribute
{
}
is there any better way to achieve this goal in a way it could be access anywhere in my project group and declared only once, without having to add its namespace (e.g by using the global namespace) to each file i use the attribute in?
Thank you
While I actually agree with P.Brian.Mackey, I think the only way to do it is exactly as DjKraze said:
Create a new micro-project of type ClassLibrary, add a single .cs file with your Coverage(..) class and ensure that class is inside no namespaces block. Then build it and for each one of the other projects do a Add-Reference to that micro-project you just created.. That way it will surely work, and you will have a handy place to put any further 'common code' to be available everywhere.
However, each project will have to be updated with the reference. This is the minimum requirement - all in all, if you want to use anything instead of copying, it must be referred..
Sorry, almost no other options for such thing!
The other way is to .. ugh, copy. You can easily set up a simple pre-build script that will copy given .cs file to each one of your projects, but "adding" the file to the .csproj's build list is a bit harder, still possible with use of some Ruby or Python or friends...
Hm.. saying that, It may be possible to write a pre-build script to inject a reference to the micro-project automatically.. But I wont know if this is worth doing. Do you have more than 50-100 projects? Else, probably it's not worth..
This only applies to VS2010 and above
If you want some source code defined in each of your projects, but without a project reference, take a look at some of the functionality provided by NuGet, especially Source Code Transformations. These allow the addition of some source code to the project when you add the NuGet package to the project.
You can use Dependency Injection
http://en.wikipedia.org/wiki/Dependency_injection
The most popular are: Microsoft Unity, Ninject, NHibernate, StructureMap, Autofac.
Good luck!

(Question on best practice) Why is "using System.Text" there by default?

Every time I creat a class, I see using System.Text that is added (amongst other using) by default. Every time I remove it after a while because it is unused according to ReSharper.
Am I missing a best practice? Do you use that namespace often? In which situation?
There has to be a reason why this namespace is referenced by default.
Thanks!
The System.Text namespace contains classes, abstract base classes and helper classes.
Say for example if you wanted to take advantage of the StringBuilder, Decoder, Encoder, etc....
The classes above, plays a significant role in most cases in .net. But it is not necessary for it to be there in your code. It only applies as to when you needed it. The important thing is to know when you will need the namespace.
It is added in visual studio by default for the convenience of the developers. Same with the
System.Linq namespace, not all of the time you will be using it but for your convenience it is already added assuming that you would be using it and that would be up to you to remove it which is by case to case basis.
Sometimes it would be a lot easier to delete it if it is not needed than to figure out the namespace and type when you need it :)
More info regarding System.Text
If it's not being used, it shouldn't be in the code. If Visual Studio adds them by default, chalk that up to Microsoft just trying to make things easy for a developer, as it thinks those are very common namespaces, but depending on what you are doing they likely aren't needed in many classes, just as you experience.
If you don't like it you can always create your own item templates. See http://msdn.microsoft.com/en-us/library/tsyyf0yh(v=VS.80).aspx
You should add using only for those namespaces that you really reference in the code.
This way the source file will not have a huge 'using header' and fewer namespace conflicts.
As you are using Resharper it is very easy to follow this rule.
If you are not using it, don't include the namespace. It is just automatically included because it is one of the more commonly used namespaces. I generally use it if I want to use regular expressions or string manipulation methods. But if you remove it and there are no compiler errors, it is safe to leave it out.

Equivalent to PHP's include in C#

What is the equivalent command to PHP's include() in C# ?
For example, PHP's include is used as so : include("ex.php");
Can I do the same in C#?
If you mean in ASP.Net using C# you can create a user control (.ascx) and add it in your .aspx page.
If you are doing MVC you can create a partial view.
The closest thing I can think of would be after creating an ascx user control named "MyUserControl"
in your page_load or pre_render :
MyUserControl cont = new MyUserControl();
this.Controls.Add(cont);
There is no such thing in C#. It's not a scripting language, so including a block of script wouldn't make sense.
What are you trying to accomplish? There are ways to do similar things in C#.
There is no direct equivalent. You use references to "link" with other CLR assemblies (access their type information), and the using directive to import namespaces.
For example, the FontCollection class is in the System.Drawing.dll assembly, and the System.Drawing.Text namespace. So you would add System.Drawing as a reference, and add the line:
using System.Drawing.Text;
I'm not sure, if this is what you want to do. But just for the case, maybe you have a look at:
<%
Response.WriteFile( "YourFile.whatever" )
%>
In addition to previous answers mentioning the using Directive and adding references to assemblies to your project (or at command line when compiling) there is a way to load other compiled .NET assemblies at runtime.
Assembly.Load will load an assembly (compiled c# file/.dll) into memory, allowing you to find and use types within that assembly. This can be used when building a plugin architecture. You publish an assembly with an interface for a plugin contract. Plugin makers can link to that that assembly and implement your interface. Your application can then load plugin assemblies, check for any types implementing your plugin interface and load and use those types into your application.
The only thing comparable in C# is using, which imports namespaces defined in assemblies referenced from the project. You cannot "include" a file in the sense that you dump the content right into your code.
For example, if your project references the System.Xml assembly, then the following code would allow you to access all of the classes in that namespace without fully qualifying their names:
using System.Xml;
This will let you use the type System.Xml.XmlDocument, for example, by specifying it as XmlDocument instead of its full type name System.Xml.XmlDocument.
There is no such thing in C#.
You're going to want to create an instance of a C# class and use that to invoke methods/attributes from other 'packages' (C# classes).
You can also use a using direction to be able to references assemblies from other projects.
Using is vaguely similar. It references another class that can then be used from that file, but it doesn't include the contents of that file directly inline.
using system;
(right at the beginning of a file)
Use this for c#
#RenderPage("header.cshtml")
This is taken from here:
http://www.w3schools.com/aspnet/showfile_c.asp?filename=try_webpages_cs_002
Although I know this post is old, but people stubming to this post can refer to it.
Well, here is what I did ... not sure if this is the right way, but it works...
In the .ascx File, specify a div as container to received the contents of included file.
<div id="containerForSomeMarkup" runat="server"></div>
In the .ascx.cs file, initialise this in the onInit() method or other methods as required...
containerForSomeMarkup.InnerHtml = File.ReadAllText("Full path of file to be included");
Coming from PHP world, for me, this approach helps keep the markup organized and intelligble...
The using keyword is what you're looking for.

basic question on C# - do I need a namespace?

I am a Java developer, totally new to C#. I am currently writing a DLL for distribution across my organization. It is a very simple library containing a couple of classes and I do not see any real use in putting all of them into some namespace just for the sake of it. Do I really have to use a namespace? If so, why? Is it some kind of a best practice?
Do you need one? No. Should you have one? Yes. It'll help prevent clashes with identically named classes in other namespaces without having to resort to the (IMHO) ugly use of global::.
For throwaway test apps (e.g. checking Stack Overflow answers), I don't use a namespace. For anything else, I do. It's just an organization thing - if you're going to reuse code, it's helpful to separate it from other code you're also reusing in the same context. What I mean is, if you're creating an app using LibraryX and LibraryY, it's useful to be able to differentiate between them within the app. It's possible that they both use the same class names, for example - which will make the code ugly if you don't use namespaces.
Aside from anything else, if you're coding with Visual Studio it's actually more work not to include a namespace - you've got to modify the project to give it an empty default namespace.
There is no need to have a namespace. However developer studio expects you to be using a name space. For example, when you choose to add a class to a project developer studio will:
Create a file for the class
Add the file to the project
Create an empty class (in the above file) that is in the project’s default namespace.
A “project’s default namespace” is a developer studio concept not a C# concept and is set in the properties of the project.
As you are creating a dll for others to use, it will be a lot easier for the users of your dll if you have a name space:
People expect you to have a namespace (so may be confused if you don’t)
Namespaces make it a lot easier for your users if you have class (or enum etc) that is named the same as another class in any dll they are linking to.
Therefore I don’t see a good reason not to use a namespace.
My vote for "yes" i think it is good habit to use namespace. you can not be sure that people won't use same class names.
To respond to your comment about naming a class the same as it's namespace, read a little bit of the following article.
Short version: don't do that.
http://blogs.msdn.com/b/ericlippert/archive/2010/03/09/do-not-name-a-class-the-same-as-its-namespace-part-one.aspx
Basically System is a root namespace in asp.net C#.
In .net every programs is create with a default name space. This default namespace is called global name space. But program itself create any numbers of namespace, each of unique name.
learn more
http://asp-net-by-parijat.blogspot.in/2015/08/what-is-namespace-in-c-need-of.html

C# - Location of using statements

One thing I have noticed a lot of back and forth on is where using statements should be placed in a C# code file- whether its in the outermost scope or inside a namespace. I understand that the location of the using statement affects the scope of the references within that file, but what I don't understand is why, in most cases, someone would ever want their using statements inside their namespace.
In almost all cases only one namespace declaration ever exists in a single file so scoping the using statements seems/(is?) useless. If one were placing multiple types and multiple namespaces in the same file then scoped using statements make perfect sense, yet I still see plenty of cases of this being done even in files with one namespace. Why?
using System;
namespace MyNamespace
{
using System.Text;
public class MyClass {
// ...
}
}
An example of this being done throughout a project seemingly unnecessarily is the ASP.NET MVC source.
Putting "using" at the top of the files is the default way of Visual Studio. However, the recommended approach is putting the "using" statements inside of the namespace. Even MS's stylecop catches this and says the default way of VS is wrong.
Both techniques work fine.
StyleCop Rule says:
Placing multiple namespace elements
within a single file is generally a
bad idea, but if and when this is
done, it is a good idea to place all
using directives within each of the
namespace elements, rather than
globally at the top of the file. This
will scope the namespaces tightly, and
will also help to avoid the kind of
behavior described above.
It is important to note that when code
has been written with using directives
placed outside of the namespace, care
should be taken when moving these
directives within the namespace, to
ensure that this is not changing the
semantics of the code. As explained
above, placing using-alias directives
within the namespace element allows
the compiler to choose between
conflicting types in ways that will
not happen when the directives are
placed outside of the namespace.
Here's some links for further review:
Should 'using' statements be inside or outside the namespace?
Is sa1200 All using directives must be placed inside the namespace (StyleCop) purely cosmetic?
http://www.hanselman.com/blog/BackToBasicsDoNamespaceUsingDirectivesAffectAssemblyLoading.aspx
http://blogs.msdn.com/sourceanalysis/pages/sa1200-usingdirectivesmustbeplacedwithinnamespace.aspx
I'd never even seen/heard of this practice until I started using StyleCop and would get flagged by rule SA1200, which I now just disable. It's odd that the .cs files that Visual Studio creates as part of a new project violate this rule by placing the using directives at the very beginning of the file, outside of the namespace.
edited, with my head hanging in shame
Ahh! The using statement you're refering to is used to import a namespace, not to wrap an IDisposable object!
Very different, ambiguous terms... you had me confused :-)
Personally I like them outside the namespace at the top of the file; but it's probably due to me switching between C# and VB.NET.
I like to organize my projects into 1-file-per-class, no inner (nested) classes, and only one class per namespace (per file) . In this situation the location of the using statement is irrelevant whether inside or outside the namespace.
The iDesign C# coding standard is a solid standard to follow (or to derive your own from). It recommends keeping the using statements outside the namespace as item #14. But it's all down to your company / project's convention

Categories