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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With