Does C # use the `use` directives of a base class inherited from a child class?

Say we have a Rectangle base class and a Square derived class:

 namespace Shapes { using System.Foo; public class Rectangle { public Rectangle(int l, int w){} } } namespace Shapes { public class Square : Rectangle public Square(int l, int w){} } 

Should the Square class explicitly indicate that it uses System.Foo ? I get erratic results. In one project, using directives seem to be inherited, but they are not in a web application.

+6
source share
5 answers

using in this context are not compiled for code - they are helpers to make your code clean for others. As a result, they are not “inherited”.

So, to answer your question, your Square class must reference System.Foo - either using the using statement, or using the fully System.Foo class name.

+7
source
Operator

A using will only apply to the next set of closing curly braces ( } ) from the level that was declared inside the same file.

 //From File1.cs using System.Baz; namespace Example { using System.Foo; //The using statement for Foo and Baz will be in effect here. partial class Bar { //The using statement for Foo and Baz will be in effect here. } } namespace Example { //The using statement for Baz will be in effect here but Foo will not. partial class Bar { //The using statement for Baz will be in effect here but Foo will not. } } 
 //From File2.cs namespace Example { //The using statement for Foo and Baz will NOT be in effect here. partial class Bar { //The using statement for Foo and Baz will NOT be in effect here. } } 
+8
source

using directives are only shared if the classes are in the same file and they are not nested in the classes, as in your example.

For instance:

 using System.Foo; namespace N { class A {} class B {} } 

If it's all in one file, A and B can use Foo .

+2
source
 using System.Foo; namespace Shapes {... 

Imports should always be the largest, not inside the namespace. This will allow the entire class structure to rely on this import when necessary.

+1
source

I think everyone lacks sense when it comes to using directives. They really have nothing to do with the class at all. using directives in the code file (.cs, .vb, etc.) are not part of the classes defined in the file. They are used by the compiler to resolve namespaces during compilation.

+1
source

Source: https://habr.com/ru/post/973384/


All Articles