Showing posts with label Dot Net. Show all posts
Showing posts with label Dot Net. Show all posts

Wednesday, September 9, 2015

Fundamental Types in .NET & C#

Programming Language: C#
Type: Tutorial
Level: Beginners
Topic Category: General Programming
Main Series: Introduction to programming in C# and the .NET framework
Topic Title: Fundamental Types in .NET & C#


Introduction
The .NET framework is special in that, unlike other programming framework, it does have a standard library of classes that is shared amongst all programming languages (PLs) targeting the .NET Framework. That means that you learn these type libraries regardless of the PL you intend to use (and regardless of the platform as the mono framework is available for other platforms)
It is good to learn the classes within the context of your PL of choice however. In this article we introduce you to the most basic types/classes in the .NET framework (I call them the "Fundamental Types").

The Mother Class: Object
Within the whole .NET framework's common type system (CTS), there's a class that all other classes are inherited from either directly or indirectly. When you declare a new class, it is also inherited from this class in some way. It is the "Object" class.
For those not familiar with inheritance, it suffices to say that no matter what is the object you are manipulating, and no matter what is the data type you are working with, it is an Object. In other words, if we declared an object reference, we can reference any object of any class. For example, all the following statements are fine and correct:
object o1 = 10;
object o2 = 'd';
object o3 = "Some string";
object o4 = DateTime.Now;
object o5 = new Student(2546, 2005, "John Doe", new DateTime(1985, 1, 1));
object o6 = 3.556;
object o7 = new int[] {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
object o8 = new Hashtable();
object o9 = new Button();
In some since, you might think of this type as being a "super-type" that can behave on behalf of all other types. For those familiar with other PLs such as VB or Basic or with Javascript, the Object type is the closest thing you'll get to a var or variant variable in those languages.

Thursday, July 10, 2008

Create an Event for a C Sharp Class

Programming Language: C#
Type: Guide, Tutorial
Level: Moderate
Topic Category: General Programming
Topic Title:
Create an Event for a C Sharp Class - Article I wrote for wikiHow


I found this new Wiki which is also powered by WikiMedia, the same organization that powers Wikipedia. It features a wiki of how-to articles wrote by volunteers, and I can't resist this. So I wrote the following article in wikiHow. It was my first contribution to the site and I hope it will not be the last. I also include it here for those not familiar with wikiHow and for my students. I kept the same article structure used in wikiHow which is designed for good how-to documents and might be not really appropriate for a blog. however, because the site is based on a Creative Commons license, I had to keep the disclaimer at the end. My Screen Name on wikiHow is C#Freak which I'm trying to use in every community from now on.

from wikiHow - The How to Manual That You Can EditMany C# programmers use events in other classes by attaching event handlers to them but have you ever wanted to implement your own event(s) in classes that you develop? This is a systematic straightforward guide to creating your own events without worrying about forgetting anything.

Steps

1. Create the Event Arguments Class:

  1. Decide what you want to communicate with your event subscribers (other programmers who will attach event handlers to your event). For example, if your event is to notify developers when a value changes, you might want to tell them the old value and the new one. If you have nothing to communicate to subscribers, use the System.EventArgs class and skip this step.
  2. Create a class named EventNameEventArgs where EventName is the name of your event
  3. Inherit the EventNameEventArgs class from System.EventArgs
  4. Create a protected field for each piece of data you want to communicate with your subscribers. For example, in an event that will notify developers of a change in a string value, you might want to tell them the old and the new strings so the fields will look like:
    protected string oldVal, newVal;
  5. Create a public property for each field you created in 1.4 that has only a get{ return fieldName;} method (where fieldName is the name of the field you created in 1.4
  6. Create a private empty constructor for the class with no implementation. The constructor should look like: private EventNameEventArgs(){}
  7. Create a public constructor for the class that takes as many arguments as there is fields/data. For example, in a string value change event, the constructor will look like:public EventNameEventArgs(string oldValue, string newValue){oldVal = oldValue; newVal = newValue;}

2. Declare the event delegate. If you did not create an event arguments class because there is no data to communicate with subscribers, use the System.EventHandler delegate and skip this step. The delegate declaration should look like: public delegate void EventNameHandler(object sender, EventNameEventArgs e);

3. Declare the event itself in the containing class: use the event handler delegate you declared/decided in 2 as the event type. The declaration should look like:public event EventNameHandler EventName;

4. Declare the event-firing method - a protected virtual method that has exactly the following declaration:protected virtual void OnEventName(EventNameEventArgs e){ if(EventName != null) { EventName(this, e); } }Use the event arguments class you decided to use in 1

5. Call the event-firing method you declared in 4 whenever the event occurs. This is the hardest part. You should know when the event you are creating will fire (what areas in your code causes the event to occur) and call the method with the appropriate event arguments class instance. For example, in the string value change event, you must see what code can cause this value to change, save its old value before the change, allow the code to change the value, create an event arguments object with the old and new values passed to the constructor and pass the object to the event-firing method.

Tips

  • Be committed to the naming convention stated in this guide, it is a de-facto standard and most .NET/Mono developers use it.
  • Do not over communicate to your subscribers. In other words, do not transfer data that is not related to the event.
  • Choose the name of your event carefully and clearly. Event names like "ValPsd" instead of "ValuePassed" is not encouraged.
  • Usually, the accessibilities used in this article is the case. However, you can change the accessibility of any declaration as long as it does not render the element changed unusable by other elements of the event creation process.
  • Examine all places in your code where the event might occur. Sometimes, more than one piece of code causes the event to fire.
  • Watch for any changes you make to your class after you declare the event. See if the change affects the triggering/firing of the event.

Warnings

If you are adding the event to a struct instead of a class, take notice of the following changes:

  1. Use "private" instead of "protected virtual" when declaring the event-firing method in 4.
  2. In the constructor of the struct that declares the event, you must initialize the event itself or you will get a compile error. Initialize events by creating new event handler delegate objects and assigning them to the event. The initialization code should look like:EventName = new EventNameHandler(); or EventNameHandler = null;

Things You'll Need

  • A .NET framework installed (either MS .NET framework on Windows or Mono on other operating systems).
  • A C# compiler (the csc tool in the MS .NET SDK, cmcs in the Mono framework, or the compiler included in .NET IDEs such as Visual Studio 2005/2008 for Windows or MonoDev for Linux).
  • The code of the class you wish to add the event to.
  • Some code editing tool (Notepad is enough, but Visual Studio, MonoDev, Notepad++ or any other editor might make development and code writing easier.
Article provided by wikiHow, a collaborative writing project to build the world's largest, highest quality how-to manual. Please edit this article and find author credits at the original wikiHow article on How to Create an Event for a C Sharp Class. All content on wikiHow can be shared under a Creative Commons license.

Monday, July 7, 2008

1) An Introduction to Designing Classes in C# - Pt.3

Programming Language: C#
Type: Tutorial
Level: Beginners
Topic Category: General Programming
Main Series:
Designing and Implementing Classes in C#
Topic Title: 1) An Introduction to Designing Classes in C# - Pt.3

Quick Review:
In part 1 of this article, we discussed classes and how to design them. We established what classes are and what they are used for and what they consist of. In part 2, we introduced the general syntax for defining classes in C# and discussed the first part of the declaration: access modifiers. In this article, we will continue discussing the declaration of classes and will introduce the different types of members of classes.

Remind me again how to declare a class in C#!
Here's a small reminder:
access-modifier [static|abstract|sealed] class class-name [: [parentClass][, implementedInterface]*]

Oh yes, I remember now. So we stopped at access modifiers. What are these three other words (static, sealed and abstract)?
I'll introduce each of these modifiers briefly. However, the concepts behind them depend on other concepts we have not discussed yet such as inheritance, polymorphism and scope.
We start with the scope modifier, static.
Static Classes
Classes are usually defined so that we can declare objects of them later. In some cases however, we only need to declare one object of the class, no more no less. For example, if we want to define a class from which we will declare an object that describes the monitor of the system, the memory of the system, the cpu of the system or perhaps, the company for which we are developing the software. Classes like that are called singleton classes. Simply, one use of static classes is to represent these classes. Static, in C#, is usually used to describe members. It means in some way: "belonging to the class itself and not to any specific object of the class". For example, if we are defining a Point class, representing geometrical point objects, we might want to run the code in one of two modes: Cartesian and polar coordinates. The fact that "points" are expressed in either format, is irrelevant to any specific "point". In fact, it affects "all" points. That's a member that belongs to the class of points as a whole not to objects of the class. Now, static classes, are by definition in C# classes with all members being static. Meaning all members of a static class has to be declared static, which in turn means they belong to the class itself. By this, we can think of the class itself as being the only object declared. Static classes are also used to group a set of methods and properties that are related by task but not belonging to any specific object. For example, a set of methods that compare/convert objects of different types in some application are all related by task, but they do not belong to a specific object as they will always behave the same no matter what object they are in (or are not in for that matter). These members are all grouped as static members of a static class. Now we discuss the second modifier: abstract
Abstract classes:
Abstract classes are used when building hierarchies of classes that are related. To fully understand this modifier, you must be familiar with inheritance and polymorphism, so I will only say, they are classes with at least one abstract member. We will discuss abstract members immediatly after inheritance. That leaves us with only one modifier: sealed
Sealed classes:
Sealed classes are simply classes that do not allow any other class to inherit from them. Again, you must be familiar with the concept of inheritance to fully understand sealed classes, and they will be revisited in inheritance
Fair enough. So, can I learn to declare my first class now, or do I have to learn inheritance first?
Actually, it will be nearly impossible and in vain to learn inhertance when you don't know how to declare members. Also, except for an empty class, classes will usually need you declare one or more members. So let's start by a brief introduction about the syntax of these members and then writing the first class?
Types of Class Members:
Classes at most, consist of Fields, Methods, Properties, Events and Nested Types. Following is a brief description of each one:
Nested Types: These are simply types nested within other types. In other words, they are types that are defined within another type. They are used when a major type needs to gather a set of information to be used only by that type. For example, a software that interacts with a hardware device might need a structure to hold the settings of the device not as seen by a high level user, but after converting them to the complex and more detailed binary values that will actually be sent to the device. Nesting types within each other is usually seen in large software libraries development to emphasize a type is only declared for the use of another type only. You nest types simply by declaring the nested type/class within the scope boundaries of the nesting class as you would normally declare any class:
class PrinterDriver {
    class hardwarePageSettings{
    }
}
Fields: fields can be thought of as being the data storage slots of the class. Fields are data (informational) members that do actually store the object's data (unlike properties). In other words, if a class having a field called "length", is used to declare objects, all objects of this class will have its own "length". That's of course if the field is not static. As we mentioned earlier, static members belong to the class, meaning only one copy of the member will be available at anytime regardless of the objects declared from that class. Well, fields are no exception! Also, we mentioned earlier that members have access modifiers. Being a data storage, you must also provide the type of data that will be stored. According to this, the simplest good field declaration will look something like:
public class MailPackage{
    public int width;
    public int height;
    public int depth;
}
Methods: are used to represent the operational attributes of a class. They can be thought of as being blocks of code that takes inputs, makes some processing and return an output. The fields of the class (and the values of these fields in object of the class) are always available to the methods in the class to read and modify. The last feature eleminates the need for long parameters list in methods. Inputs are given to the method in the form of parameters (some methods take no inputs and so have no parameters). Each parameter is defined by a data type and an alias to be used by the moethod to distinguish it from other parameters. Parameters can be passed by value (default behavior), by reference (ref parameters) and as output parameters (out parameters). C# also supports variable length parameters lists (params arguments). Here's a sample method that will take an integer and calculates its square:
public class IntegerCalculations{
    public int Squared( int x){
        return x*x;
    }
}
Properties: are fake fields, or at least, that what they look like to C++ programmers! You use a property just like you would use a field in code. However, when declared, a property is actually two methods! One is used to get the value of the fake field and an optional one that will set that value. You usually use properties for the following purposes:
  1. To act like proxies for you fields. That is, you declare private fiields and create a public property for each field that will return and set its value. This is a common practice amongst programmers because it gives you the opportunity to modify the way a field is retrieved if it was needed or may be call some method everytime the field is written to.
  2. To declare calculated fields. These are fields that do not actually need to be stored because they can be inferred/calculated from other fields in the object. An example would be the area of a circle object which can be calculated from its radius.
  3. To make a field read-only for users of the class and still be able to write to it within the class. This is done by only defining the get method of the property
An example of properties is shown below where CenterX, CenterY and Radius are accessor (proxy) properties and Area is a calculated read only property:
public class Circle{
    private double x,y,r;
    public double CenterX{get{return x;}set{x = value;}}
    public double CenterY{get{return y;}set{y = value;}}
    public double Radius{get{return r;}set{r = value;}}
    public double Area{get{return Math.PI*r*r;}}
}
Events: wil actually be fully discussed in depth along with delegates in a coming article. In brief, they provide a means for other developers who will use your class to be notified when some event of interest occurs. This is done in a Publisher-Event-Subscriber model that works as follows:
  1. You publish an event by creating an event member in your class that will be accessible by subscribers
  2. Subscribers who are interested in the event will provide a method (or more) that should be executed when the event occurs. This is called "Attaching" "Handlers" to event, where handlers are the methods subscribers provide.
  3. Whenever the event occurs within your class, you find all methods attached to the event and execute them.
An example will be in the case where you want to notify develoeprs of a change in the radius of a circle, you will declare an event within the Circle class like this:
public event
EventHandler RadiusChanged;

Events are declared as if they were fields and their type must be a delegate.
Finally, Your First Class
Here we go, the first full class (well, not exactly full, but it will do). We will develop a Name class that is capable of holding the structured information of a person's name (First Name, MiddleName, LastName)
public class Name{
  //Private fields
  private string first, middle, last;
  private string prefix, suffix;
  //Public Accessor Properties
  public string First{get{return first;}set{first = value;}}
  public string Middle{get{return middle;}set{middle = value;}}
  public string Last{get{return last;}set{last = value;}}
  public string Prefix{get{return prefix;}set{prefix = value;}}
  public string Suffix{get{return suffix;}set{suffix = value;}}
  //Public Read-Only Calculated Properties
  public string Full{get{return last + ", " + first + " " + middle;}}
}

Now that you've written your first class, the following articles, will first tackle common basic types in C# and the .NET framework. The understanding of these fundamental types and some of there commonly used members is essential to writing any code. That concludes it for today's article.

Monday, June 30, 2008

An Introduction to Designing Classes in C# - Pt.2

Programming Language: C#
Type: Tutorial
Level: Beginners
Topic Category: General Programming
Main Series:
Designing and Implementing Classes in C#
Topic Title: 1) An Introduction to Designing Classes in C# - Pt.2
Quick Review
In part 1 of this article, we discussed classes and how to design them by trying to answer the question of "What is it to declare/define a class?". We established (I hope) what classes are and what they are used for and what they consist of. We also distinguished between the informational and operational features of classes.

Introduction and familiarization
In summary, a class definition consists of defining the following members:
  • Fields: describing the informational features of the class that must be stored (some informational features are calculated so they do not need to be stored)
  • Properties: aliases for the informational features supporting doing some operations before retrieving or storing a value in the fields. They are also used for calculated informational features.
  • Methods: represent the operations the class can do or the operations an object of the class can do.
  • Events: a way to make objects of the class capable of informing other pieces of code of any event of interest.
  • Class definitions may also contain definition of other types which we call "nested types"
OK. That's fine, now how can I define a class using C#?
The simplest class declaration in C# consists of the keyword "class" followed by the name of the class followed by a pair of curly brackets "{}". For example, for the mail package class:
class MailPackage{
}

However, the complete syntax is:
access-modifier [static|abstract|sealed] class class-name [: [parentClass][, implementedInterface]*]

To fully understand this syntax, let's agree on the syntax description language I will be using to the end:
  • Italic identifiers means you need to supply it (for instance, the name of the class, its parent, etc.)
  • Lower case colored blue words: C# keywords
  • Lower case uncolored words: another coding element that needs further description (for example, the access-modifier)
  • Things in square brackets: optional items (might be included or not)
  • Things separated with a pipe (|) character: either the first or the second but not both.
  • Two things after each other, each being in square brackets: either the first or the second or both.
  • The * symbol after an item: zero or more instances of this item can be repeated
  • The + symbol after an item: one or more instances of this item can be repeated
access-modifier can be one of:
  • public
  • internal
OK, One at a time, now what are access modifiers and what do they do?
Modifiers are keywords that when introduced before a declaration, it modifies the way the declaration will normally behave. Access modifiers are modifiers related to the accessibility of a declared item. Access modifiers are used both with classes and members of classes. The decide what code can "access" the class or member. By access we mean use in the possible ways, for example, accessing a class is being able to use its name to call methods or to declare and instantiate objects. Accessing a field on the other hand means the ability to write to and read from that field. Accessing a method means being able to call the method and execute it, and accessing a property means the ability to read from and (if possible) write to the property. Finally, accessing an event is being able to attach event handlers to that event.
For classes not declared within other classes, there are two levels of accessibility: public and internal. Public classes are accessible in each and every code there is. That means you can use the class within the same assembly, in another assembly, in another country ... whatever and wherever! Internal classes can be accessed only within the same assembly it is in. For example, you can not create an object from a class that was declared internal in its assembly which is already compiled.
Do I have to specify an access modifier? and how do I decide which one to use?
Well, if you don't supply an access modifier, C# assumes it is internal making your class inaccessible anywhere outside the assembly that it belongs to. It is a good practice though to explicitly state the access modifier for you class even if it is internal. The code becomes clearer and it will be less likely that you'll accidentally hide a class that you want public.
As to how you choose, it depends. Usually, classes that are internal to the implementation of an application are declared internal. The rule of thumb is, declare all classes internal unless you want to access them from outside the assembly or you want other people to be able to. Usually, developers who develop class library for other developers to use (or even for themselves to use later on) use both public and internal classes. Application developers, especially when designing a single library unit/application/executable use all internal classes.
You said access modifier apply also to members of classes, how is that?
When you declare members, all of them can have access modifiers and have a default access level. Most members can be one of five access levels defined by the following access modifiers (ordered from highest accessibility to the lowest):

Declared accessibility

Meaning

publicAccess is not restricted.
protectedAccess is limited to the containing class or types derived from the containing class.
internalAccess is limited to the current assembly.
protected internalAccess is limited to the current assembly or types derived from the containing class.
privateAccess is limited to the containing type.

One thing to note is not to confuse accessibility with security. Access is granted to code scopes and not to persons or identities when we assign certain accessibility modifiers to classes or members. Also, although most members can have any access level, but usually, there is a scheme that goes on in most cases:
Member TypeUsual Accessibility levels (ordered from most usual)
Fieldprivate, protected, protected internal
Propertypublic, internal
Methodpublic, protected, private, protected internal, internal
Events
public

Here's the link to the accessibility modifiers in C# in MSDN:

Wednesday, June 25, 2008

An Introduction to Designing Classes in C# - Pt.1

Programming Language: C#
Type: Tutorial
Level: Beginners
Topic Category: General Programming
Main Series: Designing and Implementing Classes in C#
Topic Title: 1) An Introduction to Designing Classes in C#
- Pt.1


Most books on C# (and programming in general) will usually start with the infamous "hello world" example. Although this approach is dominant in most trainings and books, I believe it can be misleading. In my opinion, an abstract introduction to the language and the programming framework is necessary before writing any code units that really works. With object oriented programming, the situation becomes tricky! Especially with a fully object oriented programming language such as C#. In this post, I try to address some concepts that I feel must be introduced abstractly before actually beginning to learn how to write code. Now, the topics I will discuss are mere introductions in most cases and they demonstrate the concepts without tying them to a specific Programming Language (PL). I put the topics in the form of question and answer, and these topics are mainly inspired by the questions I've been asked by students during training courses I gave throughout the years especially in the early introductory phases of the courses.

What is it to declare or define a class?

We mentioned earlier that classes describe types/categories of things, more vaguely, it tells us what a single thing/object of this category will look like.
To do that, a class should list the features of objects within the class. In programming, the features of an object consists briefly of the data that describes the object and the operations that the object can do. So when we define/declare classes (I personally prefer define, however declare is the most commonly used word), what we usually do is write code units that will list the features of objects created from that class. That is, when you define a class, you should use the syntax elements your PL offers to describe and list every single feature(informational and operational) of that class.
Let's take a simple example: suppose we are designing a software for mail-courier services. The software requires at some point that you represent the mail packages that the company is dealing with. The category of objects/things that we want to represent is MailPackage objects. Congratulations, you found the name of the class you will design! Now the hard part: listing features.
To list the features of a mail package we need first to identify them (that's what we call analyzing the problem to design a solution!) As we mentioned earlier, we divide features into informational/data-related features and operational features, so let's do that!

Informational Features:
First, let's see what informational features does a mail package have. At this point, we re-emphasize the importance of the context we are developing within. You need to identify what data features that a mail package has and that is relevant to our case (mail-courier services). In other words, you need to "identify what kind of data do a mail-courier service need to store about each mail pacakge" - simple, isn't it!
Let's say that after interviewing every one in the company, their wives and their children, you found out that this is what is important to the work of the company:
Size of package: in terms of width, height and depth.
Volume of package: in meter cubed
Weight of package: in kgs rounded to the nearest integer
Order number: a serial number generated for each order that contains letters and numbers
Breakable, OneSide, Sensisitive, Hazardeous, Sealed: are all flags that can be yes or no
Packaging: one of (PaperBag, PlasticBag, CartoonBox, WoodBox, MetalBox, PlasticBox, Safe)
As you can see some of the features (let's call them properties or attributes) are calculated (Volume) and some are compund (Size). Keep that in mind for later use.

Operational Features:
Now let's take a look at what operational features does a mail package posses. When doing so, we are looking for "what mail packages can do?" Again, this should be within the context we are working within. Identifying operations can be tricky, and it much depends on the situation, but usally a good approach is generally to look for "verbs" related to the object at hand within you analysis papers. For example, you might find the following statement in one of the interview papers: "I should be able to find the order for any package that I know". Actually, the one with the information on the order is the package itself, so it is supposed to be responsible for finding its parent Order object. An operation is born: "FindParentOrder". Another type of operational features are "notifications". This enables an object of the class to notify other objects of certain things (status changes, value changes, user interactions, events in general). For example, a statement like this: "when an order is delivered, the owner should be emailed" in the interview makes a great candidate for a notification called OrderDelivered. Again, it depends on the situation but generally, notifications can be found from a statement that:
  • Is a rule of the form: "When ----- occurs, ------ should be done"
  • Is a rule of the form: "If ------ changes/occurs, ------ should change/be done"
  • Is a rule of the form: "In the case of /event of -------, ------- should be done"
Of course, again, you should tie this to the context of development. Notifications are called "events" in C# and the .NET framework in general

Tuesday, June 24, 2008

Namespaces, Assemblies and Modules

Programming Language: C#, .NET in General
Type: Tutorial
Level: Beginners
Topic Category: General Programming
Main Series: Introduction to programming in C# and the .NET framework
Topic Title: .NET Namespaces, Assemblies
and Modules

All .NET PLs share the same code cycle: Code is written, parsed, compiled into a binary MS Intermediate Language (MSIL) Assembly and then executed by the Common Language Runtime (CLR).

Simply, an assembly is a compiled .NET code. The .net framework has a common intermediate language that is as close to the Assembly language as possible which all .net PLs should compile their code into. An assembly is a binary MSIL file, thus a compiled .net code.
.NET assemblies come in three forms: Windows Executable (.exe), Console Executable (.exe) or Library (.dll)

.NET assemblies contain Modules, a piece of compiled code that is not a complete assembly. This technique is primarily for development teams with more than one person working on the same assembly. Each of them can work on a different module of the assembly and the modules are merged together to form the assembly later (this way, one assembly can be developed using more than one PL, each developer accomplishes his/her work on his favorite .net language and compiles the code to a module which is then merged with the other developers' modules to form the assembly). Now, usually, an assembly will contain only one module, but for accuracy's sake, we introduced the concept of modules.

The C# PL is a fully-object-oriented language, which means in colloquial terms "everything is a class". In .net terms, this means that C# modules can only contain class definitions, nothing more. Because assemblies are the binary MSIL binary compiled version of C# code files, this means that C# code files must not contain anything other than class definitions, and that is true. However, there is two more constructs that a C# code file can contain on its root level: namespace declaration and namespace using statements. Now, these are not memory consuming instructions like variable declaration nor are they code declaration/grouping constructs like methods. Namespaces are logical grouping of classes within a scope. They can be thought of as being prefixes to the class names of all the classes declared within them. They enable developers to create classes with globally unique names and at the same time help developers organize code within categories that you specify.

Let's take a look at a namespace declaration:

namespace GUI{
namespace DrawingShapes{

class ShapeBase{}

class Rectangle : ShapeBase{}

class Circle : ShapeBase{}

....

}

namespace Controls{

class MyControlBase{}

class MyButton : MyControlBase{}

}
namespace Text{

class MyTextBox{}

class MyRichTextBox{}

}

namespace Tools{

class Tool1{}

class Tool2{}

}

namespace InternalImplementation{

}

}

As you might have noticed, this is a clipping of a graphical user interface elements library. Now imagine two companies/developers working on the same project (GUI elements library). They both choose to develop a circle class, a rectangle class and so on. However, a developer wants to use both libraries together (may be the circle of the first company is drawn better than the one from the second company!) If there was no way to distinguish each class from the beginning, it will be impossible for the developer to use both libraries.
However, as we said, a namespace is a scope of the classes defined within it and it becomes a part of its name, so now the full name of the Circle class in this example becomes: GUI.DrawingShapes.Circle
Now, if every company/developer kept all his/her classes in a parent namespace of his choosing, it becomes nearly impossible that a naming collision will occur between his/her classes and other developers' classes. It also solves naming conflicts within the same library, for example, in an engineering design application library, you might want to develop a class that will represent the geometrical shape called Rectangle, and at the same time you want to represent a screen drawn Rectangle. These are two types sharing the same name.

Assemblies:

  • Binary compiled code files
  • Contain Modules that contain classes
  • When deciding how to divide classes on assemblies, you usually want to physically separate classes in separate files (for example, dictionary classes and drawing classes in a word processing application should be physically separated because they are both optional components of the application so they might and might not be included in the installation of the application)
  • You should always separate classes in different assemblies if they are:
    • Different plug-ins/add-ins to a container application
    • Two optional separate feature of the application
    • Perform totally unrelated tasks
  • An assembly can contain classes from different namespaces
Namespaces:
  • Logical scope of classes
  • Classes from the same namespace can span multiple assemblies
  • Is used to solve naming conflicts in classes
  • Adds a prefix to the class name
  • Is used to group similar classes (usually by task)