Introducing C# and the .NET Framework - The .NET Type Story
(Page 4 of 12 )
When you program in .NET you will define types. For example, when you define a class or a structure in C# you actually define a type of a value. Take a look at this Employee class:
class Employee
{
public string Name;
public int Age;
public string GetPosition()
{
//operations to get the position of the employee
return position;
}
}
Note: I will not explain the members of the Employee class for now but it's enough to say that this class contains two fields and one method to get the employee position.
So a Type is a representation of some values. For our Employee class example we define a type of class (Employee class) that stores one string value for the Name field and one integer value for the Age field. But we've only gone halfway, because .NET Types define a value and its associated operations.
For our example the GetPosition() method is an operation defined on the Employee class to return an Employee position. Let's take one of the .NET built in Types as an example: Int32 Type stores 4-byte integer values. C# is a type safe language, which means that if the Employee class has only two fields of type string and int then you can't store any other values in an instance of that class type. Nor can you store a string in the Age field and an integer in the Name field.
C# is also a strongly-typed language. That means if you declare a variable of type Employee then you will store (or reference) an instance of type Employee or an instance of a class that derives from Employee (more on that in a later article). Type-Safety and the Strong-Type mechanism is implied by the Common Language Runtime (CLR) at Runtime and by the C# Compiler at Design Time. You can think of this operation in a simple way: the CLR knows exactly what to do when you declare a variable of a certain type (in our example the Employee type) and also the CLR knows what are the values and operations defined in this type. So you can't write a statement that stores the character string "Michael" in a field named FirstName of an instance of the Employee class type like the following statement:
anEmployee.FirstName = "Michael";
The Compiler will generate this error
'Employee' does not contain a definition for 'FirstName'
because there is no such field defined in the class Employee. This is happening because, when you define a type (in a form of a class, structure, enumeration or anything else), the C# Compiler will emit MSIL for that type, along with metadata which tells the CLR what the type is all about. In other words the metadata introduce the Type to the Runtime and contain all the information needed at Runtime, and the CLR uses these information extensively. Some Development Environments, such as Visual Studio.NET use the metadata to express some features, such as Visual Studio IntelliSense feature.
Next: A World of .NET >>
More C# Articles
More By Michael Youssef