Using Directive/Add Reference

  • Thread starter Thread starter AA2e72E
  • Start date Start date
A

AA2e72E

With

using System.Configuration

why is ConfigurationManager.AppSettings["my"]

generate an error?

Why does the error resolve itself when, in addition to the using directive,
I add a reference to System.Configuration?

Questions:
1. I understood that the using directive made the assembly available: when
does it not do so?
2. What does Add Reference do (beyond using)?

Thanks for any explanations.
 
With

using System.Configuration

why is ConfigurationManager.AppSettings["my"]

generate an error?

Why does the error resolve itself when, in addition to the using directive,
I add a reference to System.Configuration?

Because "using" directive is not the same as adding a reference.
Questions:
1. I understood that the using directive made the assembly available: when
does it not do so?

It never does that. "using" deals strictly with namespaces - it allows
you to access members of the designated namespace without fully
qualifying them. It knows nothing about assemblies at all. For
example, all your C# programs reference "mscorlib.dll", which is the
assembly where e.g. System.Console lives, regardless of whether you
have "using System" in your code, or not.
2. What does Add Reference do (beyond using)?

It references the specified assembly, allowing you to use the types
within it - nothing less, nothing more.
 
A reference is required to say "I want to use this dll". In this case,
the code you want is in System.Configuration.dll, so you need to add a
reference to System.Configuration.dll.

A "using" statement is simply a finger-saving tool inside a single file
/ etc. It says "when resolving types, look in this namespace too". It
doesn't cause the code to import any external dlls.

Without the "using" statement, you would have to give the
fully-qualified name of the type:

System.Configuration.ConfigurationManager.AppSettings["my"]

with the "using System.Configuration;" statement, when looking for
ConfigurationManager it knows to check in the System.Configuration
namespace, so you can just type:

ConfigurationManager.AppSettings["my"].

But without the reference to the dll, neither of these will work.

Marc
 
To extend on previous answers, using is actually for giving namespaces an
alias for use in that code file so if you have a namespace called

my.really.long.namspace.which.I.Dont.want.to.type

you could put at the top

using LongOne = my.really.long.namspace.which.I.Dont.want.to.type;

then use classes in that namespace as LongOne.ClassA

When you dont put the alias = bit, the compile takes that to mean you want
the classes to be accessible without specifying the namespaces. Which is fine
unless there are classes in available class names, which you will
individually need to qualify when you use them.

Hope that helps
 
Back
Top