Walid Mashal
Walid Mashal

Reputation: 342

what is the difference between adding a using statement or writing the namespace.classname approach

what is the difference between adding a using namespace; statement and the namespace.classname approach. suppose if I want to use the XElement class I can add using System.Xml.Linq.XElement; statement to the top of the file and then use XElement class or I can use System.Xml.Linq.XElement whenever I need to use the XElement class. which one is better/efficient? which one is more of a programmers' approach?

Upvotes: 0

Views: 261

Answers (3)

Elie Saad
Elie Saad

Reputation: 312

There is no real difference between the using statement or writing the namespace.classname. It is better for readability from one way, and it's for repetitive use. Let's say i am going to use the same class in my code like 4 times, why have the trouble of re-inserting the namepsace.classname everytime? Just put the using statement once and for all.

Upvotes: 2

Rahul Jha
Rahul Jha

Reputation: 1141

Namespaces are generally used to

  • define the scope
  • Distinguish between classes with same name(but in different namespaces).

In the resulting bytecode it doesn't matter whether you had "using" or "fully qualified name" in your code. The compiler always uses the full name.Hence no performance benefit.

However what must be noted that the "using" directive helps in eliminating redundancy in code for frequently used classes of a particular namespace.

For example remove

using System;

from your code and start typing fully qualified names for all it classes.

However when two namespaces have same classes(one of which you want to use) you need to type in the fully qualified names to eliminate the Ambiguity in your code regarding which class you actually want to use.

Upvotes: 1

Peter Lange
Peter Lange

Reputation: 2876

The using statement, usually declared at the top of the class file, is a way of initializing which namespaces to try to attribute the classes used within that class or module. From a compiler perspective, every class is resolved to its full namespace at compile (simplifying a bit here, I know) so there really is no performance benefit.

From a readability perspective, it is nicer to see code such as

FileInfo f = new FileInfo(Path.Combine("Dir","FileName"));

rather than

System.IO.FileInfo f = new System.IO.FileInfo(System.IO.Path.Combine("Dir","FileName"));

The former option is easier to type and read. But neither is "better" or "more efficient"

Upvotes: 2

Related Questions