Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# using directive depth

Tags:

c#

I'm trying to understand the c# using directive...Why does this work...

using System;
using System.ComponentModel.DataAnnotations;
namespace BusinessRuleDemo
{
    class MyBusinessClass
    {
        [Required]
        public string SomeRequiredProperty { get; set; }
    }
}

but this does not?

using System;
using System.ComponentModel;
namespace BusinessRuleDemo
{
    class MyBusinessClass
    {
        [DataAnnotations.Required]
        public string SomeRequiredProperty { get; set; }
    }
}

The second results in a compile error "The type or namespace DataAnnotations cannot be found. Are you missing are missing a using directive or an assembly reference?

like image 743
Shawn de Wet Avatar asked Jul 20 '11 18:07

Shawn de Wet


2 Answers

using directive makes it possible to use class names from the namespace you specified as its argument. Since DataAnnotations is not a class, but a namespace, it's not accessible in second case. You should either use fully qulified class names NS1.NS2.Class1, or start you program with using NS1.NS2; and then use Class1.

like image 115
Andrey Agibalov Avatar answered Oct 29 '22 04:10

Andrey Agibalov


Because you can either use Fully Qualified Class Names or just use the ClassName and let .NET resolve it via using directive. There is no middle ground.

Class1 -

NameSpace1.NameSpace2.NameSpace3.Class1

can be accessed as

using NameSpace1.NameSpace2.NameSpace3;
...
... Class1.DoSomething();
...

or

...
NameSpace1.NameSpace2.NameSpace3.Class1.DoSomething();
...

but not like

using NameSpace1.NameSpace2;
...
NameSpace3.Class1.DoSomething();
...

In last case what compiler would actually be looking for is root namespace NameSpace3 which clearly does not exist. It won't try to look for System.NameSpace3 or NameSpace1.NameSpace3 or NameSpace1.NameSpace2.NameSpace3 etc etc.

like image 33
YetAnotherUser Avatar answered Oct 29 '22 03:10

YetAnotherUser