why we give reference to the other projects? - c#

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

Related

Global using directive in c#

I'd like to create a namespace in c# that can be found in any project. Not just the one that it is located in. like the system namespace. Is that possible and if yes I'd like to know how.
I already googled and didn't find anything
Classes in the System namespace are part of the Base Class Library (BCL) that gets included as part of the .NET Runtime. The only way for you to have your class be as globally accessible as, say, the System.String class, would be to convince Microsoft to add your class into their BCL. That is rare, but not unheard of. The IObservable<> interface is an example of a type that was added that way.
However, there are tons of classes that people are using every day without having them added to the BCL. If you're willing to accept one additional step for people to take with their projects, in order to leverage your project, you can publish your project's output as a Nuget package. Then people only need to add your Nuget package (referenced by its package name), and they'll have access to the public API defined by the types in your DLLs.
Consumers of your package will still need to reference the namespaces of the types they want to use, either explicitly or via a using directive. In C#, a "global using directive" only makes the namespace globally available within the project that the directive is found in.
If you only want your types to be accessible from other projects found in the same solution, Nuget isn't necessary: you can add a project reference.
There are a lot of nuances I'm glossing over (i.e. differences between namespaces and DLLs and packages), but which it would be helpful for you to read about.
One of solution:
You need to create library(DLL) and refernce it in projects.
If you using visual studio 201x you can create project with type class library.
The library namespaces can be found use like this ´using MyNamespace;´
example of class in library:
adding refernce to project:
example of using your own class library:

Conflict between Azure and Microsoft.Azure namespaces

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.

Should System be explicitly imported in a Xamarin.Android class file?

I'm pruning out unnecessary using directives, and am not sure if I should leave
using System;
in all my files or not?
In a Xamarin.Android Visual Studio class file, this directive
imports the namespace defined in
...\Reference Assemblies\Microsoft\Framework\MonoAndroid\v1.0\System.dll
However, I have many files that are not explicitly using any types from there (which can be indicated by the faded/grayed syntax highlighting). However, it is my understanding that .NET primitives are aliases that the compiler substitutes for types within the System namespace (int <=> System.Int32), so I'm not sure if this could potentially cause any issues. The compiler never throws any kind of ambiguity error if omitted (between .NET System and Xamarin System), and my testing so far hasn't resulted in any issues.
You ask that question because you have a misunderstanding between the using directive and referenced assemblies.
using does not reference any assembly.
The References added to your project do (s. the "References" node in the Solution Explorer, or "Dependencies" in .NET Core projects), hence their name, References.
using only allows you to shortcut using namespaces or types available in the previously separately referenced assemblies in your code, e.g. writing Console.WriteLine() instead of System.Console.WriteLine().
You may ask why this differentation has been made in the first case. Well, one issue would be that if you had two assemblies defining types with the same name (let's say, some XBox related assembly also providing a Console type) and you would also reference the assemblies with the using directive as you were thinking, there'd be no way to differ between System.Console or XBox.Console in code, as there are now two Console types accessible at the "same time".
To come back to reality, you can remove any using directives which are grayed out with absolutely no impact on how your application behaves as the references to the assemblies will still stay intact (nothing in the "References" node in your Solution Explorer will have changed), and so your application will still be able to access the types defined in System - just you won't be able to use them like Int32 instead of System.Int32 for example.
Now the joke about the primitive types is that C# provides keywords to shortcut those types like Int32 at any time (no matter if you have using System; on top of your file or not) by writing simply int, or bool for System.Boolean, and so on. That's the reason why your directive is grayed out, because you used those primitive types (if at all) through their keyword. Replace one int with the actual type name Int32 and you'll see the directive not being grayed out anymore.
If it's greyed out then yup, delete it. You don't need it for primitive types, only for objects inside that namespace such as DateTime or Guid.
Using directives have nothing to do with what assemblies are in use, only to help the compiler resolve types that are not qualified with namespaces. Any greyed out using can be deleted.

c# Where can I lookup Microsoft Namespace names?

I'm using a MS namespace but Visual Studio is telling me I don't have a reference to it. Is there a place you can go to and lookup namespaces?
Thanks
If you mean "to find which dll I need (per-type)": MSDN?
For example, CLSID
Namespace: Microsoft.Aspnet.Snapin
Assembly: AspNetMMCExt (in AspNetMMCExt.dll)
You can normally find the MSDN page about a specific namespace by going to http://msdn.microsoft.com/namespace. So, for example, to find out about System.Web you could go to...
http://msdn.microsoft.com/system.web
That in itself doesn't help you. You'll need to click through from there to the specific types you're using, and it'll tell you (near the top) the name of the DLL that implements the type.
Remember that a namespace can contain types that are defined in more than one DLL.
See http://msdn.microsoft.com/en-us/library/wkze6zky(VS.80).aspx for how to add a reference
You will also need the assembly.
For Microsoft and System namespaces the easiest way is http://msdn.microsoft.com/library or, if MSDN installed locally, its index.
If you want to know which assembly a certain class is located in you can simply check the documentation (it's noted on the class overview page of the class). Note that one namespace might very well be spread out over more than one assembly.
You need to first add reference to the DLL before using it in your code with the 'using' keyword.
Right click the project > add reference > in the .Net tab select the component and click ok. Then build your code.
You can't find the DLL for a specified namespace in all cases because multiple types belonging to the same assembly may reside in different assemblies.
The fastest way to get there would be to google to the MSDN page for the specific type (class) you are using. Let's say XDocument.. I put `msdn xdocument class' into google. First result is the page I need. Click!
Under the class name you'd see a section like this
Namespace: System.Xml.Linq
Assembly: System.Xml.Linq (in System.Xml.Linq.dll)
This shows you the namespace that the type belongs to (for which you may need to add a using in your code)
and the DLL you need to 'Add Reference' to.

Referencing namespaces globally?

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.

Categories

Resources