In last two lessons, I took minimalist approach towards classes. I kept things as simple as possible for everyone to understand. Now there are few concepts that we need to cover, as a part of our Windows Phone 7.5 Mango Apps Development tutorial series, before we move from C# to XAML.
In this lesson, we will learn about namespaces. In .NET framework, all classes and methods in library are organized into namespaces. Namespaces can be considered as last name for a class. So there might be many “Harry”s in the world but we can identify the one we want using last name and that is, “Potter”.
Likewise many classes share the same name in .NET framework, but namespaces remove ambiguity. So if we want to use class having same name as some other class, namespace can help compiler in identifying the one we want.
Consider this line of code:
System.IO.IsolatedStorage.IsolatedStorageSettings mySettings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
Here we are creating instance of Isolated Storage settings class and everything behind that is namespace for that class (System.IO.IsolatedStorage). One thing that should be noted here that we will learn more about isolated storage on day three so do not be concerned about what it does. We have used this example just to show you what namespaces are!
Now you must be thinking about the length of the code. But to shorten this sentence, .NET framework has provided “using” statement. “Using” statement has access to all the namespaces and classes that belongs to those namespaces. So in a way, you are telling compiler that hey, before complaining go and check those namespaces which I am using.
Now check the top part of C# file (See image). You will see that visual studio has already piled many namespaces which you most probably would use. All the unused namespaces are ignored by the compiler. If you have no idea about the namespace in which the class you want resides, then start writing the class name. After completing it, you will get a red line beneath it telling that compiler hasn’t understood the statement and a small blue line to the start of class name which tells us that it has found the class name in one or more namespaces. Now hit “Ctrl” + “.” It will open a dialog box, using which you can add namespace.
So this is all about the namespaces you need to know at the moment. You can create your own namespaces but that is an advance topic which we shall not attend. See you in next part where we will talk of Collections.