Microsoft StyleCop provided a warning when the using directives for namespaces are provided outside of the namespace. Is this really required as my view on this is that using dircetives for namespaces is for providing a alias name for namespace and for removing the need for providing the namespace name when a class/interface is used. I dont think it will be used for loading the assembly.
It's basically your choice. But as we follow Microsoft and this is their standard it's good to have your all usings inside your name space. And also have them sorted.
Related
I'm trying to understand C# namespaces. Suppose two namespaces exist with the same name and they have identical contents, i.e. all classes and methods also have identical names. How can the compiler distinguish between the two if I try to call a method, e.g. MyMethod in class MyClass in namespace MyNamespace? It's not likely a real-world scenario, but I find the information useful for understanding purposes.
Second question: When I dot on a namespace, e.g. System, I get a set of related namespaces like System.Configuration etc., but when I go to Microsoft's documentation I cannot find any namespace named Configuration contained in System namespace. Why is that? I can of course find the namespace if I look for System.Configuration, but I don't understand why the System.Configuration namespace is not nested inside the System namespace.
If you have two types that have the same name and same number of type parameters, and exist in the same namespace, then the assemblies that they are in must be different.
If your project references the assembly that one type is in, but not the other, then you will obviously only be able to refer to the type that is from the assembly that you referenced. If your project references both assemblies, then there will be a compiler error, like this. To fix it, you can use an extern alias.
Not being able to find System.Configuration in this page is merely due to how Microsoft organises their documentation. They have decided to list all the namespaces out here, rather than display a hierarchy. Note that System.Configuration is part of the .NET Platform Extensions, not plain old .NET, so you have to choose that in the dropdown.
I needed to add a new reference to my code, so I added Azure.Messaging.ServiceBus via the nuget package manager. That installation went through successfully, and I can see that in the references for my package.
However, when I attempt to add using Azure.Messaging.ServiceBus to a given file, it cannot find it, from what I can tell because there are other references to Microsoft.Azure.X, and the Azure namespace is routed to the Microsoft.Azure namespace.
I was able to temporarily escape that issue by adding the reference outside of the namespace in the following way:
#pragma warning disable SA1200 // Using directives must be placed correctly
//using Azure.Messaging.ServiceBus;
#pragma warning restore SA1200 // Using directives must be placed correctly
namespace X.Y.Z
{
using System;
...
using Microsoft.Azure.ResourceProvider.Common.Exceptions;
...
However, this is somewhat of a pain because I then have to add this to many classes and also it is preventing me from doing things like using the fully qualified object name for Azure.Messaging.ServiceBus.ServiceBusMessage to not conflict with another class that is already named ServiceBusMessage within my solution.
Is there something I can do to have Azure.Messaging.ServiceBus be treated like any other import and not have it conflict with existing references?
Using statements are to help readability, not really for performance.
Suppose the kind of using directive in the Headers section (using statements section), is to bring a namespace into scope where as the fully qualified namespace (Eg: System.Text.StringBuilder) - this kind of statement is for correctly using (creating and disposing) an object implementing the IDisposable interface.
The <fully-qualifed-type-name> is the name of the type whose static members and nested types can be referenced without specifying a type name. If you don't provide a fully qualified type name, C# generates compiler error CS0246 as referenced from this MSFT Doc.
And As Panagiotis Kanavos suggested that, another option is to use two or more files to separate the classes/methods which needs access to each namespace.
Glad Nimish Todi, that you are trying to,
Resolve the issue by refactoring out the code to make the classes do only their own functionalities instead of making changes many at this time where aliasing of the import does helps to.
When looking at a solution with multiple projects:
1) Why do we add a reference to the other project? Can't we just use inheritance?
2) After we add the reference by using Visual Studio, why do we have to add the project to the namespace system? For example: using myReferenceProject; I thought that the IDE would do that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using myReferenceProject;
using System.Data.SqlClient;
using System.Data;
1) why we give reference to the other project? cant we just use inheritance???
They're two completely different concepts.
Adding a reference to another assembly basically says, "I want to be able to use some of this code. Please make the compiler aware that this code exists, and optionally copy it into the output directory so that it's present at execution time too."
How would you expect to use inheritance to create a class derived from some type if the compiler has no knowledge of that type?
2) after we give the reference by using the visual studio IDE why we have to add the project to the namespace system???
Because assemblies and namespaces are different concepts too. A using directive simply says to the compiler "When I refer to type Foo within my code, look in these namespaces to try to resolve it." That type could come from any of the assemblies you've referenced.
It's really important that you understand the difference between assemblies and namespaces. Even though they're often named similarly (Foo.Bar.dll often provides types in the namespace Foo.Bar) they're conceptually different.
The project is a self sufficent compilable unit, that has to compile into the valid assembly file. That's why you need esplicitly specifiy which referencies every project needs in order to be able to compile separately from others.
There is no any inheritance concept on projects level.
1) why we give reference to the other project? cant we just use inheritance?
This question makes no sense. What does inheritance have to do with project references. Can you elaborate?
2) after we give the reference by using the visual studio IDE why we have to add the project to the namespace system?
Because there's an inherent difference between an assembly referencing another assembly (which is what happens when you add a reference to the project) and the language knowing where to find a class which is what happens when you use the using directive in a file.
For example, suppose you create a class in your project called TextBox. Then in another file you want to use that class. How would the language know whether you are referring to your custom TextBox class or another one in a referenced assembly? The answer to that question is namespaces. By fully-qualifying the class name with its namespaces, you tell the compiler which class you're using.
The using directive is a way to specifying the namespace once per file instead of every time you use the class (or other classes in that namespace). So if you need to reference your TextBox class multiple times within a single file, you wouldn't want to have to write this every time:
MyCodebase.MyAssembly.MyNamespace.MyOtherNamespace.SomethingElse.TextBox
Instead, you include a using directive of the entire namespace, so you only have to write this:
TextBox
I'm using StyleCop and FxCop tools to improve my code but I came to a place where there are two rules, one in StyleCop and one in FxCop that exclude each other. If I fix my code to match the rule from StyleCop then FxCop validation fails and vice versa.
First rule is SA1200 from StyleCop which says that all using directives must be placed inside of the namespace.
All using directives must be placed inside of the namespace.
So I have done something like this
namespace MyNamespace
{
using System;
...
}
It was ok for StyleCop, no more warnings. Now I run FxCop validation and it tells me that CA1014 is violated:
Mark 'MyApp.dll' with CLSCompliant(true) because it exposes externally visible types.
To resolve this I should do something like this:
[ClsCompliant(true)]
namespace MyNamespace
{
...
}
but now I cannot build my project because ClsCompliant attribute is not recognized (because it's from System namespace which I include inside of the MyNamespace). So if I move using System; directive outside of MyNamespace declaration. This will make my code compile but again it will break the rule from StyleCop.
Is there any way to deal with this problem except for disabling one of the rules in StyleCop or FxCop? And if that's not possible which of the rules should I disable? Which is less important?
Use full attribute name:
[System.CLSCompliant(true)]
namespace MyNamespace
{
...
}
BTW: if you want to mark your whole assembly as CLSCompliant, put
[assembly: System.CLSCompliant(true)]
in Properties/AssemblyInfo.cs file
My suggestion is to turn off the "All using directives must be placed inside of the namespace." rule in StyleCop. It's impractical to adhere to it, especially since most of the code generators (even VS own ones) do not follow this practice.
Is there a way to reference a namespace globally across the whole solution?
So instead of having these lines in every code file:
using System;
using MyNamespace;
having to declare them only once, and every code file would use them.
Btw I am using Visual Studio.
No, C# doesn't have this concept. Each source file is independent in this respect. (And if the using directives are in a namespace declaration, those are independent from other using directives in peer namespace declarations, too. That's a pretty rare case though in my experience.)
You don't need ReSharper to change what gets included in a new class though. You can use the Visual Studio templates.
EDIT: Just to clarify the point about using directives within namespaces, suppose we had (all in one file):
using Foo;
namespace X
{
using Bar;
// Foo and Bar are searched for code in here, but not Baz
}
namespace Y
{
using Baz;
// Foo and Baz are searched for code in here, but not Bar
}
Usually I only have one namespace declaration in a file, and put all the using directives before it.
No, this is not possible.
If you're using ReSharper, you can set an option to include specific using directives in every new file you create though.
From this SO question and follow-up blog post. You can edit the Visual Studio default templates.
To do this, look at the file in this zip : [Program Files][Visual Studio]\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
and modify the Class.cs file as needed. Additionally, Visual Studio may have cached this file here :
[Program Files][Visual Studio]\Common7\IDE\ItemTemplatesCache\CSharp\Code\1033\Class.zip
In C# 10.0 you can use Global Usings.
global using System;
global using MyNamespace;
No, you can not reference a namespace globally across the whole solution in .NET or .NET CORE.
But you can use project wise namespace globally in solution. this feature will be available from c#10/.NET 6. currently it's in preview but it will be released in NOV 2021
=========Project level .NET 6 global using namespace=========
Create a class file at root of the project e.g GlobalNamespace.cs
global using System;
global using System.Linq;
global using System.Text.RegularExpressions;
global using System.Threading.Tasks;
Then you don't need to declare using namespace in other .cs files of the project which are already declared globally.
As others have mentioned Visual Studio Templates are the way to go.
Note that simply adding a using statement to your template will not ensure that the compiler can resolve your types. So, if you are adding a using statement for MyNamespace in every class you may need to add an assembly reference to your project as well. See the C# FAQ for more information.
One trick I miss as a newb to CSharp is to look at the "refences" (in VS), to right click and "Add New Reference". This is especially handy when combining mulitple projects where I have made some generic class for reuse elsewhere.