.NET Development Foundation/System Types: Difference between revisions

From Wikibooks, open books for an open world
Jump to navigation Jump to search
[unreviewed revision][unreviewed revision]
Content deleted Content added
m restore current version
Line 1: Line 1:
<noinclude>
{{delete|continuing exam 70-536 consolidation, content has been moved [[Microsoft_Certified_Technology_Specialist/Exam_70-536/System_Types#Nullable_type|hre]], please move history before deleting --&nbsp;[[User:Jacques Bergeron|Jacques]]&nbsp;([[User talk:Jacques_Bergeron|talk]])&nbsp;([[Special:Emailuser/Jacques Bergeron|email]]) 05:28, 13 December 2007 (UTC)}}
[[../Introduction|Previous]] / [[../Services|Next]]
<div style="text-align:center;font: 2em sans-serif;padding;1em">System types and collections</div>


[[Exam 70-536|&lt; Exam 70-536]]


</noinclude>
''Original text for this page authored by [[User:Scott98390|William "Scott" Baker]]''
==System types and collections==


'''Exam objective: '''Developing applications that use system types and collections.
==Grammar==
value-type := struct-type | enum-type


===Topics===
struct-type := type-n


====System types====
nullable-type := non-nullable-value-type ?


{{wikipedia|data type}}
non-nullable-value-type := type
{{wikipedia|type system}}
This section will be obvious for experienced object oriented developers but some of the specific objectives of the exam are directly related to the type system.

Types are a way to classify the concepts or objects of a language. The way this classification is organized is called a type system. The types themselves can also be categorized in different ways by the type system.

The first way to categorize types in .NET is to make a difference between types that are part of the framework class libraries (System types) and types that will be constructed by the developer (custom types).

Writing object oriented programs can be seen as the process of defining one or more custom types. Those types are then packaged in some kind of execution unit (Assemblies in the case of .NET). The assemblies are compiled and then executed starting at some entry point that will be a specified method of one of the custom type.

Those custom types use:
* System types to execute "pre-programmed" instruction sequences
* other custom types

System types are also packaged in assemblies. The custom assemblies must reference the system assemblies in order to use the System types.

There are other ways to categorize types in .NET. One of them is by the way the objects created based on those types are mapped to the computer memory. This will give us Value types and Reference types.

Another way is by Reflection category (Class, Value types, Interfaces, Generics, etc.).

Yet another way is to distinguish the types that are directly supported by the runtime (built-in types) from those defined either in the class libraries or custom.

Those categories can also be intersected with one another, that will give us such things has "Built-in value types" or "System interfaces". Stay alert of the categorizations used when you encounter such combinations.

{{todo|short description of namespaces should go here}}

In the context of namespaces the System types are the types included in the System namespace or one of its sub-namespace and Custom types (non system types) should use other namespaces.

For a peek at how Microsoft describes the .NET type system see [http://msdn2.microsoft.com/en-us/library/2hf02550.aspx MSDN]. And then for an overview of the the class libraries (System types) see [http://msdn2.microsoft.com/en-us/library/hfa3fa08.aspx MSDN].

Most of the exam is in fact based on how to use the common parts of the type libraries (System types). This is why the list of exam objectives (and this book TOC) is so long.

====Hello world====

For the newcomers to .NET, you may want to take a little break from the concepts here and make sure that you see how the concepts discussed so far are used in a very simple example. The next concepts are not that trivial. We will put such an example [[#Hello world example|here]].

====Value types====

{{wikipedia|Call_stack}}
Value types represent one part of the Value / Reference classification of the type system.

An instance of a value type directly contains its data (value). For example an Int32 local variable has its memory allocated directly on the stack.

The value types are themselves split in 3 categories:
* The built-in value types
* User-defined value types
* Enumerations

Remember that built-in types are the types directly supported by the runtime.

They are the building blocks of any program because they are what the machine instructions ultimately act upon. The rest are essentially compositions of those types.

All of the built-in types are value types except for Object and String.

The built-in value types consist of
* the integer types (Byte, SByte, Int16, Int32, Int64, UInt16, UInt32 and UInt64)
* the floating point types (Single and Double)
* the logical type (Boolean)
* other (Char, Decimal, InPtr and UInPtr)

All built-in value type are defined in the System namespace (ex. System.Int32) and have keywords that represent them in the VB and C# (ex. int in C#) except for InPtr and UInPtr.

{{dynamic navigation
|title=Side note
|body=
We noted above that type classification can be quite confusing sometimes. As an example note that System.DateTime is presented as a built-in value type in the [[../Trailers/#70-536 Training kit|Training kit]] (page 5) and this is not identified as an error in MSDN KB. It is '''not''' a built-in type according to the [[../Trailers/#ECMA 335|official specification]] (page 19). The confusion comes from the fact that the [[../Trailers/#70-536 Training kit|Training kit]] does not make a clear difference between System types (in the class librairies) and Build-in types (basic types dealt with directly by the runtime).

The point here is not to be fussy or depreciate the work done by the authors of the training kit. We just want to note that it may be worth to take a few minutes to clearly separate the concepts before heading to the code.
}}

All value types derive from System.ValueType either directly for built-in and user-defined or indirectly thru System.Enum for unemerations.

Enumerations are a way to name a set of values of an underlying integer type (signed or unsigned). As restrictions of an integer type they act as their underlying type.

User-defined value types and Enumerations both include System types and Custom types.

An example of a System user-defined value-type would be System.Drawing.Point used in drawing.

You build custom value types using specific language contructs (struct in C#).

An example of a System enumeration would be the System.Data.CommandType enumeration that specifies if a table is a text command, a call to a stored procedure, etc.

You build custom enumerations using specific language contructs (enum in C#).

====Reference types====

{{wikipedia|Dynamic_memory_allocation}}
Reference types represent the other part of the Value / Reference classification of the type system.

Contrary to value types an instance of a reference type does not directly contains its data (value) but instead some kind of a reference to to the memory location of that value. For example a String local variable has memory allocated on the stack for a reference to the contained string not the string itself. In that case the string itself will be allocated on the heap and garbage collected (more on that later).

Two built-in types are considered reference types: Object and String and they are also directly referenced in the System libraries (ex. System.String) and have their own contructs in the .NET languages (ex. string in C#).

The reference types are themselves split in four categories :
* pointers
* arrays
* classes
* interfaces

We will not talk about pointers in this book because no exam objective reference them.

The next three sections will prent arrays, classes and interfaces

For a comparaison of value / reference types you can try [http://blogs.msdn.com/theoy/archive/2005/06/24/ValueRef.aspx this].

====Arrays====

{{todo|obviously a short discussion of arrays is missing here :-)}}

====Classes====

{{wikipedia|Object_oriented_programming}}
Classes are themselves split in three :
* user-defined classes
* boxed value types
* delegates

Boxed value types will be discussed a little later in the [[#Boxing and unboxing|boxing / unboxing]] section.

Delegates will also be covered later in their [[#Events and delegates|section]].

User-defined classes are the basic realizations of the object oriented concepts.

Obviously a lot can be said about classes but since no exam objective reference to them we will assume that the reader is already familiar with the concept and have already worked with them (in .NET or elsewhere).

You can have System classes (hundreds and hundereds of them) and custom classes (where you will code the essential of your porgram logic).

====Interfaces====

{{wikipedia|Type_polymorphism}}
If you want to get really confused on what exactly is object-oriented programming just check the Wikipedia article on Polymorphism :-).

The idea is just to be able to have a single type of reference to the "common part" of diffetent types that have "something in common".

Rectangles and Ellipses are both "Shapes" so how can we get part of a program to manipulate "Shapes" without knowing about the specific of Rectangles or Ellipses. In such a situation we say that Shapes are polymorphic (literally they can take many forms).

In object-oriented programming you get this behavior with inheritance. A reference to a parent class (Shape) will manipulate child objects (Rectangles or Ellipses) without problems.

Interfaces where developped to get the same behavior in the context of component-based computing where you don't have access to the source code so you cannot use inheritance. The interface construct was the basis of all component communication in COM.

An interface is a contract to implement a set of methods in a clearly defined manner (method signatures). If you know that a class implements an interface you know that you can use any of the defined methods.

From that definition it is easy to imagine having a reference to an "interface instance" from which you can call any of the interface mathods. So easy in fact that the framework provides just that.

Now suppose that instead of a Shape beeing a parent of Rectangle we just have a Shape interface that is implemented both by Rectangle and Ellipse. If I have a reference to a Rectangle object, I will be able to "cast" it to a reference to a Shape interface and pass ot to the part of the program that knows only about "Shape objects".

This is exactly the same polymorphic behavior that we had via inheritance.

The class librairies rely heavily on interfaces and a clear understanding of the concept is essential.

====Attributes====

{{wikipedia|Aspect-oriented programming}}
We now take a short break of our discussions on types to talk a little bit about attributes. First of all attributes are not types. They are elements of information that are added to a program element (assemblies, classes, method, etc.) to qualify it outside of the normal code associated with that element.

Those added "attributes" serves at doing manipulations of the underlying program element without having to modify the execution logic of the element.

Why would we ever want to manipulate program elements outside excution code? The short answer here is that object oriented concepts do not easily deal with what is known as cross-cutting concerns, or aspects of a program that apply to all or most classes. Examples of such aspects are security, persistence, serialization, etc. Instead of modifying every class to add serialization logic (which has nothing to do with business rules) you can add serialization attributes to the class to direct the serialization process of those classes without changing the business logic (execution code).

A number of functionality of the framework rely on attributes to add information to program elements. The attributes are kept by the compilation process and associated with their qualifying element in the assemblies. They are analysed programmatically at run time using reflexion to adjust the behavior of "cross-cutting" fuctionalities.

As for types we have System attributes (part of the framework) and Custom attributes (built by the developer). The development of Custom attribute will ne trated in the reflexion section. Until then we will limit ourselves with System attributes and focus on defining them and knowiing how they will determine the behavior of framework.

The attributes usage section will give some example of how simple System attributes can be used.

Lets note here that attributes are not the only way to add "non-execution" information to a program to modify its behavior. XML configuration files for example can be used to specify parameters that will affect program execution. We will talk about those in the Configuration section of this book.

See [http://msdn2.microsoft.com/en-us/library/aa288059(VS.71).aspx MSDN] for the discussion of attributes in C#.

====Collections====

{{wikipedia|Collection_%28computing%29}}
A collection is a grouping of objects. The framework has many types of collections that cover most of the situations where want to process objects as a group. Knowing these collection types will save you the time to "re-code" equivalent logic and keep your program more maintainable.

For a tutorial see [http://samples.gotdotnet.com/quickstart/howto/doc/icollection.aspx GotDotNet]

For some "prescriptive guidance" see [http://www.aspnetresources.com/blog/dotnet_collection_madness.aspx AspNetResources]

The major drawback of collections is that in "real life" objects that are grouped together usually have some characteristics in common (they are the same type, have a common parent type or support a common interface). So most of the time we know "more" about the objects then marely their organization. Collections do not allow us to use that knowledge to validate the objects passed to the collection or code logic applicable to all objects of the collection (without casting and exception handling that is).

Generic collections where introduced in version 2.0 of the framwork. They this problem while keeping the other advantages of collections. For that reason they should be used instead of "plain" collections.

====Generics====

{{wikipedia|Generic_programming}}
Generic programming or the use parametrized types is not an object oriented concept. In that sense Generics are a bit like attributes, they were added to main stream object-oriented platforms to take care of situations that are not easily covered by object-oriented techniques.

To start our disucssion please read the following interesting [[../Generic types|linked article]] that introduces the concept of generics in the context of generic collections. This external [http://www.softsteel.co.uk/tutorials/cSharp/lesson21.html tutorial] does the same.

====Exceptions====

{{wikipedia|Exceptions}}

====Specialized (collections)====

====System Interfaces====

====Events and Delegates====

===Classes, Interfaces, and tools===

====Hello world example====

{{dynamic navigation
|title=[[C# Code sample]]
|body=
Hello world example
using System;
using System.Collections.Generic;
using System.Text;
namespace HelloWorldLab1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello world!");
Console.WriteLine("Press ENTER to exit");
Console.ReadLine();
}
}
}

Note: when you create a new console project in Visual studio, all the code is generated by default except for the 3 "Console" lines in the Main method. Just add those 3 lines and run the program.

We have discussed all the parts of that program except for the role of the Console which will be discussed in the input/output section (Stream). For now lets say that it is a System class, in the System namespace (the "using System" instruction maker the "System." part of "System.Console.Writeline()" optional) and that the WriteLine() and ReadLine() methods write and read strings to and from the console.
}}

====System types====

'''Exam objective: '''Manage data in a .NET Framework application by using the .NET Framework 2.0 system types.

(Refer System namespace)

=====Value types usage=====

Following are some "usage" oriented remarks about value types.

Value types contain the values they are assigned:
int a = 1; <font color=green>// the variable "a" contains "1" of value type ''int''</font>
Value types can also be created by using the ''new'' keyword. Using the ''new'' keyword initializes the variable with the default value obtained from the type's default constructor:
int a = new int(); <font color = green>// using the default constructor via the ''new'' keyword</font>
return a; <font color=green>// returns "0" in the case of type Int.</font>
Value types can be declared without being initialized, but they must be initialized to some value before being used:
int a; <font color=green>// This is perfectly acceptable</font>
return a; <font color=green>// NOT acceptable! You can't use "a" because "a" doesn't have a value!</font>
Value types cannot equal ''null''. .NET 2.0 provides a ''Nullable type'' to get around this limitation, which is discussed in [http://en.wikibooks.org/wiki/Study_Guides:Microsoft_Certified_Professional_Developer_%28MCPD%29%5CExam_70-536%5CNullable_type the next section], but ''null'' is not a valid value for value types:
int a = null; <font color=green>// Won't compile - throws an error.</font>
If you copy a Value type to another Value type, the value is '''copied'''. Changing the value of the copy has no effect on the value of the original. The second is merely a copy of the first - they are in no way connected after assignment. This is fairly intuitive:
int var1 = 1;
int var2 = var1; <font color=green>//the value of var1 (a "1" of type ''int'') is '''copied''' to var2</font>
var2 = 25; <font color=green>// The "1" value in var2 is overwritten with "25"</font>
Console.WriteLine("The value of var1 is {0}, the value of var2 is {1}", var1, var2);
Which would result in the output:
The value of var1 is 1, the value of var2 is 25
Changing the value of the copy ('''var2''' in this instance) had no effect on the value of the original ('''var1''').
This is different from reference types which copy a reference to the value, not the value itself.

Value types cannot be derived from.

=====Nullable type=====

See [http://msdn2.microsoft.com/en-us/library/1t3y8s4s.aspx MSDN]


==Nullable Types Overview==
A nullable type...
A nullable type...


*Is a genreic type
*Is an instance of System.Nullable struct.
*Is an instance of System.Nullable struct.
*Can only be declared on value types.
*Can only be declared on value types.
Line 26: Line 289:
Be careful with ''nullable'' booleans! In ''if, for, while'' or logical evaluation statements a nullable boolean will equate a ''null'' value with ''false'' -- it will '''not''' throw an error.
Be careful with ''nullable'' booleans! In ''if, for, while'' or logical evaluation statements a nullable boolean will equate a ''null'' value with ''false'' -- it will '''not''' throw an error.


==Methods: ''T GetValueOrDefault()'' & ''T GetValueOrDefault(T defaultValue)''==
Methods: ''T GetValueOrDefault()'' & ''T GetValueOrDefault(T defaultValue)''<br>
Returns the stored value or the default value if the stored value is set to ''null''.
Returns the stored value or the default value if the stored value is set to ''null''.


==Properties: ''HasValue'' & ''Value''==
Properties: ''HasValue'' & ''Value''<br>
Nullable types have two '''read only''' properties: ''HasValue'' and ''Value''.
Nullable types have two '''read only''' properties: ''HasValue'' and ''Value''.


Line 43: Line 306:
return MyInt; <font color=green>// returns ''null''.</font>
return MyInt; <font color=green>// returns ''null''.</font>


==Wrapping / Unwrapping==
'''Wrapping / Unwrapping'''

'''Wrapping''' is the process of [[packaging]] a value ''m'' from a non-nullable type ''N'' to a nullable type ''N?'' via the expression '''new N?(m)'''.<br/>
'''Unwrapping''' is the process of [[evaluating]] a nullable type ''N?'' for instance m as type ''N'' or NULL and is performed via the 'Value' property (eg '''m.Value''').<br/>
'''Wrapping''' is the process of packaging a value ''m'' from a non-nullable type ''N'' to a nullable type ''N?'' via the expression '''new N?(m)'''

<br/>
'''Unwrapping''' is the process of [[evaluating]] a nullable type ''N?'' for instance m as type ''N'' or NULL and is performed via the 'Value' property (eg '''m.Value'''). <br>

Note: Unwrapping a null instance generates the exception ''System.InvalidOperationException''
Note: Unwrapping a null instance generates the exception ''System.InvalidOperationException''


==The ?? Operator (aka the ''Null Coalescing'' Operator)==
'''The ?? Operator''' (aka the ''Null Coalescing'' Operator)

While not for use solely with Nullable types, the '''??''' operator proves very useful when you want to use a default value instead of a ''null'' value. The '''??''' operator returns the left operand of a statement if not null, otherwise it returns the right operand.
While not for use solely with Nullable types, the '''??''' operator proves very useful when you want to use a default value instead of a ''null'' value. The '''??''' operator returns the left operand of a statement if not null, otherwise it returns the right operand.
int? MyInt = null;
int? MyInt = null;
Line 55: Line 321:
For more information see the [http://blog.devstone.com/Aaron/archive/2006/01/02/1404.aspx blog entry by R. Aaron Zupancic on the ?? Operator]
For more information see the [http://blog.devstone.com/Aaron/archive/2006/01/02/1404.aspx blog entry by R. Aaron Zupancic on the ?? Operator]


=====Using a user-defined value type=====
[[User:Scott98390|Scott Baker]] 01:13, 27 February 2006 (UTC)

=====Building a value type=====


=====Using enumerations=====


=====Building an enumration=====

=====Using reference types=====

Reference types are more commonly referred to as ''objects''. [http://msdn2.microsoft.com/en-us/library/0b0thckt.aspx Classes], [http://msdn2.microsoft.com/en-us/library/87d83y5b.aspx Interfaces] and [http://msdn2.microsoft.com/en-us/library/900fyy8e.aspx Delegates] are all reference types, as well as the built-in reference types '''System.Object''' and '''System.String'''. Reference types are stored in managed Heap memory.

Unlike Value types, reference types can be assigned the value ''null''.

Copying a reference type copies a ''reference'' that points to the object, not a copy of the object itself. This can seem counter-intuitive at times, since changing a copy of a reference will also change the original.

A Value type stores the value it is assigned, plain and simple - but a Reference type stores a ''pointer to a location in memory'' (on the heap). Think of the heap as a bunch of lockers and the Reference type holds the locker number (there are no locks in this metaphor). Copying a Reference type is like giving someone a copy of your locker number, rather than a copy of its contents. Two Reference types that point to the same memory is like two people sharing the same locker - both can modify its content:
{{dynamic navigation
|title=[[C# Code sample]]
|body=
Example of using Reference types
public class Dog
{
private string breed;
public string Breed { get {return breed;} set {breed = value;} }
private int age;
public int Age { get {return age;} set {age = value;} }
public override string ToString()
{
return String.Format("is a {0} that is {1} years old.", Breed, Age);
}
public Dog(string dogBreed, int dogAge)
{
this.breed = dogBreed;
this.age = dogAge;
}
}
public class Example()
{
public static void Main()
{
Dog myDog = new Dog("Labrador", 1); <font color=green>// myDog points to a position in memory.</font>
Dog yourDog = new Dog("Doberman", 3); <font color=green>// yourDog points to a ''different'' position in memory.</font>
yourDog = myDog; <font color=green>// both now point to the same position in memory,
// where a Dog type has values of "Labrador" and 1</font>
yourDog.Breed = "Mutt";
myDog.Age = 13;
Console.WriteLine("Your dog {0}\nMy dog {1}", yourDog.ToString(), myDog.ToString());
}
}
Since the yourDog variable and the the myDog variable both point to the same memory store, the ouput of which would be:
Your dog is a Mutt that is 13 years old.
My dog is a Mutt that is 13 years old.
}}

=====Using and building arrays=====

=====Using classes=====

=====Building a custom class=====

=====Using interfaces=====

=====Building a custom interface=====

=====Using attributes=====

=====Using generic types=====

The use of the four major categories of System Generic Types will be done elsewhere:
* The nullable type was discussed above
* A whole section follows on Generic collections
* The generic event handler will be discussed in the Event / Delegate section.
* The generic delegates will also be discussed in the Event / Delegate section as well as in the Generic collections section (Comparer class).

=====Building a generic type=====

The programming of a custom generic collection was shown in the [[/Generic types|article]] mentioned in the topics discussion.

{{todo|could be fun to have an example of a custom generic type that is not related to arrays or collections}}

=====Exception classes=====

Some links to MSDN:
*Exceptions and exception handling - [http://msdn2.microsoft.com/en-us/library/ms173160.aspx MSDN]
*Handling and throwing exceptions - [http://msdn2.microsoft.com/en-us/library/5b2yeyab.aspx MSDN]
*Exception Hierarchy - [http://msdn2.microsoft.com/en-us/library/z4c5tckx.aspx MSDN]
*Exception Class and Properties - [http://msdn2.microsoft.com/en-us/library/5whzhsd2.aspx MSDN]

=====Boxing and unboxing=====

See [http://msdn2.microsoft.com/en-us/library/yz2be5wk.aspx MSDN]

All types derive diretly or indirectly from System.Object (including value types by the way of System.ValueType). This allows the very convenient concept of a reference to "any" object but poses some technical concerns because value types are not "referenced". Comes boxing and unboxing.

Boxing and unboxing enable value types to be treated as objects. Boxing a value type packages it inside an instance of the Object reference type. This allows the value type to be stored on the garbage collected heap. Unboxing extracts the value type from the object. In this example, the integer variable i is boxed and assigned to object o:
int i = 123;
object o = (object) i; // boxing

Please also note that it is not necessary to explicitly cast an integer to an object (as shown in the example above) to cause the integer to be boxed. Invoking any of its methods would also cause it to be boxed on the heap:

int i=123;
String s=i.toString(); //This call will cause boxing

There is also a third way in which a value type can be boxed. That happens when you pass a value type as a parameter to a function that expects an object.
Let's say there is a function prototyped as:

void aFunction(value as Object)

Now let's say from some other part of your program you call this function like this:

int i=123;
aFunction(i); //i is automatically boxed

This call would automatically cast the integer to an object, thus resulting in boxing.

The object o can then be unboxed and assigned to integer variable i:
o = 123;
i = (int) o; // unboxing

'''Performance of boxing and unboxing'''

In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally.

=====TypeForwardedToAttribute Class=====

See [http://msdn2.microsoft.com/en-us/library/system.runtime.compilerservices.typeforwardedtoattribute.aspx MSDN]

:For a discussion of TypeForwardToAttribute in the CLR see [http://msdn2.microsoft.com/en-us/library/ms404275(ide).aspx MSDN]

:Other possible links: [http://www.heege.net/blog/PermaLink,guid,8d076332-4fb0-44b5-a829-4c4d653de2d6.aspx Marcus' Blog], [http://notgartner.wordpress.com/2005/11/19/70-536-forwarding-types/ NotGartner]

====Using Collections====

'''Exam objective: '''Manage a group of associated data in a .NET Framework application by using collections.

(Refer System.Collections namespace - [http://msdn2.microsoft.com/en-us/library/system.collections(vs.71).aspx MSDN])

=====ArrayList class=====

see [http://msdn2.microsoft.com/en-us/library/system.collections.arraylist.aspx MSDN]

The ArrayList class is used for arrays whose size will dynamically increase as required. An ArrayList is not necessarily sorted.

<font color="blue">using</font> System;
<font color="blue">using</font> System.Collections;
<font color="blue">public class</font> Demo {
<font color="blue">public static void</font> Main() {
ArrayList myArrayList = new ArrayList();
myArrayList.Add("Testing");
myArrayList.Add("1...2...3");
}
}

=====Collection interfaces=====

:[[Study Guides:Microsoft Certified Professional Developer (MCPD)\Exam 70-536\ICollection interface and IList interface|ICollection interface and IList interface]]

:IComparer interface, IEqualityComparer interface, and IKeyComparer interface

::IComparer interface - [http://msdn2.microsoft.com/en-us/library/system.collections.icomparer.aspx MSDN]

::IEqualityComparer interface - [http://msdn2.microsoft.com/en-us/library/system.collections.iequalitycomparer.aspx MSDN]

::IKeyComparer interface - '''IKeyComparer does not exist in .Net 2.0'''

:IDictionary interface and IDictionaryEnumerator interface

::IDictionary interface - [http://msdn2.microsoft.com/en-us/library/system.collections.idictionary.aspx MSDN]

::IDictionaryEnumerator interface - [http://msdn2.microsoft.com/en-us/library/system.collections.idictionaryenumerator.aspx MSDN]

:[[Study Guides:Microsoft Certified Professional Developer (MCPD)\Exam 70-536\IEnumerable interface and IEnumerator interface|IEnumerable interface and IEnumerator interface]]

:IHashCodeProvider interface - [http://msdn2.microsoft.com/en-us/library/system.collections.ihashcodeprovider.aspx MSDN] - '''Interface is now obsolete (as of .NET 2.0)'''

[[Study Guides:Microsoft Certified Professional Developer (MCPD)\Exam 70-536\Iterators|Iterators]]

Hashtable class - [http://msdn2.microsoft.com/en-us/library/system.collections.hashtable.aspx MSDN]

:Used to represent a collection of key/value pairs.

CollectionBase class and ReadOnlyCollectionBase class

:CollectionBase class - [http://msdn2.microsoft.com/en-us/library/system.collections.collectionbase.aspx MSDN]

:ReadOnlyCollectionBase class -[http://msdn2.microsoft.com/en-us/library/system.collections.readonlycollectionbase.aspx MSDN]

DictionaryBase class and DictionaryEntry class

:DictionaryBase class - [http://msdn2.microsoft.com/en-us/library/system.collections.dictionarybase.aspx MSDN]

:DictionaryEntry '''structure''' - [http://msdn2.microsoft.com/en-us/library/system.collections.dictionaryentry.aspx MSDN]

Comparer class - [http://msdn2.microsoft.com/en-us/library/system.collections.comparer.aspx MSDN]

Queue class - [http://msdn2.microsoft.com/en-us/library/system.collections.queue.aspx MSDN]

SortedList class - [http://msdn2.microsoft.com/en-us/library/system.collections.sortedlist.aspx MSDN]

BitArray class - [http://msdn2.microsoft.com/en-us/library/system.collections.bitarray.aspx MSDN]

Stack class - [http://msdn2.microsoft.com/en-us/library/system.collections.stack.aspx MSDN]

====Generic collections====

'''Exam objective: '''Improve type safety and application performance in a .NET Framework application by using generic collections.

(Refer System.Collections.Generic namespace [http://msdn2.microsoft.com/en-us/library/system.collections.generic(vs.80).aspx MSDN ])

Collection.Generic interfaces

:see also [http://www.ondotnet.com/pub/a/dotnet/excerpt/progcsharp4_ch09-04/index.html ONDotnet]

:Generic IComparable interface - [http://msdn2.microsoft.com/en-us/library/4d7sx9hd(VS.80).aspx MSND]

::(Refer System Namespace)

:Generic ICollection interface and Generic IList interface

::Generic ICollection interface - [http://msdn2.microsoft.com/en-us/library/92t2ye13.aspx MSDN]

::Generic IList interface - [http://msdn2.microsoft.com/en-us/library/5y536ey6.aspx MSDN]

:Generic IComparer interface and Generic IEqualityComparer interface

::Generic IComparer interface - [http://msdn2.microsoft.com/en-us/library/8ehhxeaf.aspx MSDN]

::Generic IEqualityComparer interface - [http://msdn2.microsoft.com/en-us/library/ms132151.aspx MSDN]

:Generic IDictionary interface - [http://msdn2.microsoft.com/en-us/library/s4ys34ea.aspx MSDN]

:Generic IEnumerable interface and Generic IEnumerator interface

::Generic IEnumerable interface - [http://msdn2.microsoft.com/en-us/library/9eekhta0.aspx MSDN]

::Generic IEnumerator interface - [http://msdn2.microsoft.com/en-us/library/78dfe2yb.aspx MSDN]

::IHashCodeProvider interface - [http://msdn2.microsoft.com/en-us/library/system.collections.ihashcodeprovider.aspx MSDN] - '''Interface is now obsolete (as of .NET 2.0)'''

Generic Dictionary

:Generic Dictionary class and Generic Dictionary.Enumerator structure

::Generic Dictionary class - [http://msdn2.microsoft.com/en-us/library/xfhwa508.aspx MSDN]

::Generic Dictionary.Enumerator structure - [http://msdn2.microsoft.com/en-us/library/k3z2hhax.aspx MSDN]

:Generic Dictionary.KeyCollection class and Dictionary.KeyCollection.Enumerator structure

::Generic Dictionary.KeyCollection class - [http://msdn2.microsoft.com/en-us/library/3fcwy8h6.aspx MSDN]

::Dictionary.KeyCollection.Enumerator structure - [http://msdn2.microsoft.com/en-us/library/8a7wk24w.aspx MSDN]

:Generic Dictionary.ValueCollection class and Dictionary.ValueCollection.Enumerator structure

::Generic Dictionary.ValueCollection class - [http://msdn2.microsoft.com/en-us/library/x8bctb9c.aspx MSDN]]

::Dictionary.ValueCollection.Enumerator structure - [http://msdn2.microsoft.com/en-us/library/ax9d1dzh.aspx MSDN]]

Generic Comparer class and Generic EqualityComparer class

:Generic Comparer class - [http://msdn2.microsoft.com/en-us/library/cfttsh47.aspx MSDN]

:Generic EqualityComparer class - [http://msdn2.microsoft.com/en-us/library/ms132123.aspx MSDN]

Generic KeyValuePair structure - [http://msdn2.microsoft.com/en-us/library/5tbh8a42.aspx MSDN]

Generic List class, Generic List.Enumerator structure, and Generic SortedList class

:Generic List class - [http://msdn2.microsoft.com/en-us/library/6sh2ey19.aspx MSDN]
::A generic list class instance is simply declared using the List<T> syntax where T is the specific type.
:Generic List.Enumerator structure - [http://msdn2.microsoft.com/en-us/library/x854yt9s.aspx MSDN]

:Generic SortedList class - [http://msdn2.microsoft.com/en-us/library/ms132319.aspx MSDN]

Generic Queue class and Generic Queue.Enumerator structure

:Generic Queue class - [http://msdn2.microsoft.com/en-us/library/7977ey2c(VS.80).aspx MSDN]

:Generic Queue.Enumerator structure - [http://msdn2.microsoft.com/en-us/library/1ttzy8a4(VS.80).aspx MSDN]

Generic SortedDictionary class - [http://msdn2.microsoft.com/en-us/f7fta44c.aspx MSDN]

:For differences between SortedList and SortedDictionary are explained see [http://msdn2.microsoft.com/en-us/5z658b67.aspx MSDN]

Generic LinkedList

:A Generic Linked List represents a doubly linked list and is a general-purpose linked list. It supports enumerators and implements the ICollection interface, consistent with other classes in the .NET Framework.

:Generic LinkedList class - [http://msdn2.microsoft.com/en-us/library/he2s3bh7(VS.80).aspx MSDN]

:Generic LinkedList.Enumerator structure - [http://msdn2.microsoft.com/en-us/library/2s4xk11f.aspx MSDN]

:Generic LinkedListNode class - [http://msdn2.microsoft.com/en-us/library/ahf4c754(VS.80).aspx MSDN]

Generic Stack class and Generic Stack.Enumerator structure

:Generic Stack class - [http://msdn2.microsoft.com/en-us/library/3278tedw.aspx MSDN]

:Generic Stack.Enumerator structure - [http://msdn2.microsoft.com/en-us/library/x2bb46cs.aspx MSDN]

====Specialized collections====

'''Exam objective: '''Manage data in a .NET Framework application by using specialized collections.

(Refer System.Collections.Specialized namespace)

=====Specialized String classes=====

:StringCollection class - [http://msdn2.microsoft.com/en-us/library/system.collections.specialized.stringcollection.aspx MSDN]

:StringDictionary class - [http://msdn2.microsoft.com/en-us/library/system.collections.specialized.stringdictionary.aspx MSDN]
:StringEnumerator class - [http://msdn2.microsoft.com/en-us/library/system.collections.specialized.stringenumerator.aspx MSDN]

=====Specialized Dictionary classes=====

:HybridDictionary class - [http://msdn2.microsoft.com/en-us/library/system.collections.specialized.hybriddictionary.aspx MSDN]
:IOrderedDictionary interface and OrderedDictionary class

::IOrderedDictionary Interface - [http://msdn2.microsoft.com/en-us/library/system.collections.specialized.iordereddictionary.aspx MSDN]

::OrderedDictionary class - [http://msdn2.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx MSDN]

:ListDictionary class - [http://msdn2.microsoft.com/en-us/library/system.collections.specialized.listdictionary.aspx MSDN]

=====Named collections=====

:NameObjectCollectionBase class - [http://msdn2.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary.aspx MSDN]

:NameObjectCollectionBase.KeysCollection class - [http://msdn2.microsoft.com/en-us/library/system.collections.specialized.nameobjectcollectionbase.keyscollection.aspx MSDN]

:NameValueCollection class - [http://msdn2.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection.aspx MSDN]

=====CollectionsUtil class=====

CollectionsUtil class - [http://msdn2.microsoft.com/en-us/library/system.collections.specialized.collectionsutil.aspx MSDN]

=====BitVector32 structure and BitVector32.Section structure=====

:BitVector32 structure - [http://msdn2.microsoft.com/en-us/library/system.collections.specialized.bitvector32.aspx MSDN]

:BitVector32.Section structure - [http://msdn2.microsoft.com/en-us/library/system.collections.specialized.bitvector32.section.aspx MSDN]

====Standard interfaces====

'''Exam objective: '''Implement .NET Framework interfaces to cause components to comply with standard contracts.

(Refer System namespace)

IComparable interface - [http://msdn2.microsoft.com/en-us/library/system.icomparable(vs.71).aspx MSDN]

:The IComparable interface defines a comparison method that a value type or class implements to create a type-specific comparison method

IDisposable interface - [http://msdn2.microsoft.com/en-us/library/system.idisposable.aspx MSDN]

:The '''IDispose''' interface can be used to explicitly release unmanaged resources in custom classes. The consumer of an object can call this method when the object is no longer needed.

:The .Net garbage collector releases memory allocated to '''managed''' objects when they are no longer used, however, it is not possible to predict when garbage collection will occur and ''it has no knowledge of unmanaged resources such as window handles, or open files and streams.''

IConvertible interface - [http://msdn2.microsoft.com/en-us/library/system.iconvertible.aspx MSDN]

ICloneable interface - [http://msdn2.microsoft.com/en-us/library/system.icloneable.aspx MSDN]

INullableValue interface - [http://msdn2.microsoft.com/de-de/library/system.inullablevalue.aspx MSDN]

IEquatable interface - [http://msdn2.microsoft.com/en-us/library/ms131187.aspx MSDN]

IFormattable interface - [http://msdn2.microsoft.com/en-us/library/system.iformattable.aspx MSDN]

====Events and delegates====

'''Exam objectives: '''Control interactions between .NET Framework application components by using events and delegates.
(Refer System namespace)

[[Study Guides:Microsoft Certified Professional Developer (MCPD)\Exam 70-536\Delegate class|Delegate class]]
EventArgs class - [http://msdn2.microsoft.com/en-us/library/system.eventargs.aspx MSDN]


EventHandler delegates - [http://msdn2.microsoft.com/en-us/library/system.eventhandler(VS.80).aspx MSDN]
==External links==
* [http://msdn2.microsoft.com/en-us/library/1t3y8s4s.aspx MSDN2 Entry for Nullable Types]
* [http://msdn.microsoft.com/vcsharp/2005/overview/language/nullabletypes/ Visual C# Developer Center : Nullable Types]
* [http://www.bozemanblog.com/PermaLink,guid,df10036b-d9b7-480d-9b56-79816639b9d2.aspx Bill Bozeman's Blog Entry on Nullable Types]


<noinclude>
[[Category:Microsoft Certified Professional Developer]]
[[../Introduction|Previous]] / [[../Services|Next]]
</noinclude>
[[Category:Microsoft_Certified_Professional_Developer]]

Revision as of 17:43, 13 December 2007

Previous / Next

System types and collections


System types and collections

Exam objective: Developing applications that use system types and collections.

Topics

System types

This section will be obvious for experienced object oriented developers but some of the specific objectives of the exam are directly related to the type system.

Types are a way to classify the concepts or objects of a language. The way this classification is organized is called a type system. The types themselves can also be categorized in different ways by the type system.

The first way to categorize types in .NET is to make a difference between types that are part of the framework class libraries (System types) and types that will be constructed by the developer (custom types).

Writing object oriented programs can be seen as the process of defining one or more custom types. Those types are then packaged in some kind of execution unit (Assemblies in the case of .NET). The assemblies are compiled and then executed starting at some entry point that will be a specified method of one of the custom type.

Those custom types use:

  • System types to execute "pre-programmed" instruction sequences
  • other custom types

System types are also packaged in assemblies. The custom assemblies must reference the system assemblies in order to use the System types.

There are other ways to categorize types in .NET. One of them is by the way the objects created based on those types are mapped to the computer memory. This will give us Value types and Reference types.

Another way is by Reflection category (Class, Value types, Interfaces, Generics, etc.).

Yet another way is to distinguish the types that are directly supported by the runtime (built-in types) from those defined either in the class libraries or custom.

Those categories can also be intersected with one another, that will give us such things has "Built-in value types" or "System interfaces". Stay alert of the categorizations used when you encounter such combinations.


Clipboard

To do:
short description of namespaces should go here


In the context of namespaces the System types are the types included in the System namespace or one of its sub-namespace and Custom types (non system types) should use other namespaces.

For a peek at how Microsoft describes the .NET type system see MSDN. And then for an overview of the the class libraries (System types) see MSDN.

Most of the exam is in fact based on how to use the common parts of the type libraries (System types). This is why the list of exam objectives (and this book TOC) is so long.

Hello world

For the newcomers to .NET, you may want to take a little break from the concepts here and make sure that you see how the concepts discussed so far are used in a very simple example. The next concepts are not that trivial. We will put such an example here.

Value types

Value types represent one part of the Value / Reference classification of the type system.

An instance of a value type directly contains its data (value). For example an Int32 local variable has its memory allocated directly on the stack.

The value types are themselves split in 3 categories:

  • The built-in value types
  • User-defined value types
  • Enumerations

Remember that built-in types are the types directly supported by the runtime.

They are the building blocks of any program because they are what the machine instructions ultimately act upon. The rest are essentially compositions of those types.

All of the built-in types are value types except for Object and String.

The built-in value types consist of

  • the integer types (Byte, SByte, Int16, Int32, Int64, UInt16, UInt32 and UInt64)
  • the floating point types (Single and Double)
  • the logical type (Boolean)
  • other (Char, Decimal, InPtr and UInPtr)

All built-in value type are defined in the System namespace (ex. System.Int32) and have keywords that represent them in the VB and C# (ex. int in C#) except for InPtr and UInPtr.

Side note

We noted above that type classification can be quite confusing sometimes. As an example note that System.DateTime is presented as a built-in value type in the Training kit (page 5) and this is not identified as an error in MSDN KB. It is not a built-in type according to the official specification (page 19). The confusion comes from the fact that the Training kit does not make a clear difference between System types (in the class librairies) and Build-in types (basic types dealt with directly by the runtime).

The point here is not to be fussy or depreciate the work done by the authors of the training kit. We just want to note that it may be worth to take a few minutes to clearly separate the concepts before heading to the code.

All value types derive from System.ValueType either directly for built-in and user-defined or indirectly thru System.Enum for unemerations.

Enumerations are a way to name a set of values of an underlying integer type (signed or unsigned). As restrictions of an integer type they act as their underlying type.

User-defined value types and Enumerations both include System types and Custom types.

An example of a System user-defined value-type would be System.Drawing.Point used in drawing.

You build custom value types using specific language contructs (struct in C#).

An example of a System enumeration would be the System.Data.CommandType enumeration that specifies if a table is a text command, a call to a stored procedure, etc.

You build custom enumerations using specific language contructs (enum in C#).

Reference types

Reference types represent the other part of the Value / Reference classification of the type system.

Contrary to value types an instance of a reference type does not directly contains its data (value) but instead some kind of a reference to to the memory location of that value. For example a String local variable has memory allocated on the stack for a reference to the contained string not the string itself. In that case the string itself will be allocated on the heap and garbage collected (more on that later).

Two built-in types are considered reference types: Object and String and they are also directly referenced in the System libraries (ex. System.String) and have their own contructs in the .NET languages (ex. string in C#).

The reference types are themselves split in four categories :

  • pointers
  • arrays
  • classes
  • interfaces

We will not talk about pointers in this book because no exam objective reference them.

The next three sections will prent arrays, classes and interfaces

For a comparaison of value / reference types you can try this.

Arrays

Clipboard

To do:
obviously a short discussion of arrays is missing here :-)


Classes

Classes are themselves split in three :

  • user-defined classes
  • boxed value types
  • delegates

Boxed value types will be discussed a little later in the boxing / unboxing section.

Delegates will also be covered later in their section.

User-defined classes are the basic realizations of the object oriented concepts.

Obviously a lot can be said about classes but since no exam objective reference to them we will assume that the reader is already familiar with the concept and have already worked with them (in .NET or elsewhere).

You can have System classes (hundreds and hundereds of them) and custom classes (where you will code the essential of your porgram logic).

Interfaces

If you want to get really confused on what exactly is object-oriented programming just check the Wikipedia article on Polymorphism :-).

The idea is just to be able to have a single type of reference to the "common part" of diffetent types that have "something in common".

Rectangles and Ellipses are both "Shapes" so how can we get part of a program to manipulate "Shapes" without knowing about the specific of Rectangles or Ellipses. In such a situation we say that Shapes are polymorphic (literally they can take many forms).

In object-oriented programming you get this behavior with inheritance. A reference to a parent class (Shape) will manipulate child objects (Rectangles or Ellipses) without problems.

Interfaces where developped to get the same behavior in the context of component-based computing where you don't have access to the source code so you cannot use inheritance. The interface construct was the basis of all component communication in COM.

An interface is a contract to implement a set of methods in a clearly defined manner (method signatures). If you know that a class implements an interface you know that you can use any of the defined methods.

From that definition it is easy to imagine having a reference to an "interface instance" from which you can call any of the interface mathods. So easy in fact that the framework provides just that.

Now suppose that instead of a Shape beeing a parent of Rectangle we just have a Shape interface that is implemented both by Rectangle and Ellipse. If I have a reference to a Rectangle object, I will be able to "cast" it to a reference to a Shape interface and pass ot to the part of the program that knows only about "Shape objects".

This is exactly the same polymorphic behavior that we had via inheritance.

The class librairies rely heavily on interfaces and a clear understanding of the concept is essential.

Attributes

We now take a short break of our discussions on types to talk a little bit about attributes. First of all attributes are not types. They are elements of information that are added to a program element (assemblies, classes, method, etc.) to qualify it outside of the normal code associated with that element.

Those added "attributes" serves at doing manipulations of the underlying program element without having to modify the execution logic of the element.

Why would we ever want to manipulate program elements outside excution code? The short answer here is that object oriented concepts do not easily deal with what is known as cross-cutting concerns, or aspects of a program that apply to all or most classes. Examples of such aspects are security, persistence, serialization, etc. Instead of modifying every class to add serialization logic (which has nothing to do with business rules) you can add serialization attributes to the class to direct the serialization process of those classes without changing the business logic (execution code).

A number of functionality of the framework rely on attributes to add information to program elements. The attributes are kept by the compilation process and associated with their qualifying element in the assemblies. They are analysed programmatically at run time using reflexion to adjust the behavior of "cross-cutting" fuctionalities.

As for types we have System attributes (part of the framework) and Custom attributes (built by the developer). The development of Custom attribute will ne trated in the reflexion section. Until then we will limit ourselves with System attributes and focus on defining them and knowiing how they will determine the behavior of framework.

The attributes usage section will give some example of how simple System attributes can be used.

Lets note here that attributes are not the only way to add "non-execution" information to a program to modify its behavior. XML configuration files for example can be used to specify parameters that will affect program execution. We will talk about those in the Configuration section of this book.

See MSDN for the discussion of attributes in C#.

Collections

A collection is a grouping of objects. The framework has many types of collections that cover most of the situations where want to process objects as a group. Knowing these collection types will save you the time to "re-code" equivalent logic and keep your program more maintainable.

For a tutorial see GotDotNet

For some "prescriptive guidance" see AspNetResources

The major drawback of collections is that in "real life" objects that are grouped together usually have some characteristics in common (they are the same type, have a common parent type or support a common interface). So most of the time we know "more" about the objects then marely their organization. Collections do not allow us to use that knowledge to validate the objects passed to the collection or code logic applicable to all objects of the collection (without casting and exception handling that is).

Generic collections where introduced in version 2.0 of the framwork. They this problem while keeping the other advantages of collections. For that reason they should be used instead of "plain" collections.

Generics

Generic programming or the use parametrized types is not an object oriented concept. In that sense Generics are a bit like attributes, they were added to main stream object-oriented platforms to take care of situations that are not easily covered by object-oriented techniques.

To start our disucssion please read the following interesting linked article that introduces the concept of generics in the context of generic collections. This external tutorial does the same.

Exceptions

Specialized (collections)

System Interfaces

Events and Delegates

Classes, Interfaces, and tools

Hello world example

Hello world example

   using System;
   using System.Collections.Generic;
   using System.Text;
   namespace HelloWorldLab1
   {
       class Program
       {
           static void Main(string[] args)
           {
               Console.WriteLine("Hello world!");
               Console.WriteLine("Press ENTER to exit");
               Console.ReadLine();
           }
       }
   }

Note: when you create a new console project in Visual studio, all the code is generated by default except for the 3 "Console" lines in the Main method. Just add those 3 lines and run the program.

We have discussed all the parts of that program except for the role of the Console which will be discussed in the input/output section (Stream). For now lets say that it is a System class, in the System namespace (the "using System" instruction maker the "System." part of "System.Console.Writeline()" optional) and that the WriteLine() and ReadLine() methods write and read strings to and from the console.

System types

Exam objective: Manage data in a .NET Framework application by using the .NET Framework 2.0 system types.

(Refer System namespace)

Value types usage

Following are some "usage" oriented remarks about value types.

Value types contain the values they are assigned:

int a = 1;  // the variable "a" contains "1" of value type int

Value types can also be created by using the new keyword. Using the new keyword initializes the variable with the default value obtained from the type's default constructor:

int a = new int(); // using the default constructor via the new keyword
return a;          // returns "0" in the case of type Int.

Value types can be declared without being initialized, but they must be initialized to some value before being used:

int a;     // This is perfectly acceptable
return a;  // NOT acceptable!  You can't use "a" because "a" doesn't have a value!

Value types cannot equal null. .NET 2.0 provides a Nullable type to get around this limitation, which is discussed in the next section, but null is not a valid value for value types:

int a = null;  // Won't compile - throws an error.

If you copy a Value type to another Value type, the value is copied. Changing the value of the copy has no effect on the value of the original. The second is merely a copy of the first - they are in no way connected after assignment. This is fairly intuitive:

int var1 = 1;
int var2 = var1;  //the value of var1 (a "1" of type int) is copied to var2
var2 = 25;        // The "1" value in var2 is overwritten with "25"
Console.WriteLine("The value of var1 is {0}, the value of var2 is {1}", var1, var2);

Which would result in the output:

The value of var1 is 1, the value of var2 is 25

Changing the value of the copy (var2 in this instance) had no effect on the value of the original (var1). This is different from reference types which copy a reference to the value, not the value itself.

Value types cannot be derived from.

Nullable type

See MSDN

A nullable type...

  • Is a genreic type
  • Is an instance of System.Nullable struct.
  • Can only be declared on value types.
  • Is declared with System.Nullable<type> or the shorthand type? - the two are interchangeable.
System.Nullable<int> MyNullableInt;  // the long version 
int? MyNullableInt;                  // the short version
  • Accepts the normal range of values of the underlying type, as well as null.
bool? MyBoolNullable;  // valid values: true || false || null

Be careful with nullable booleans! In if, for, while or logical evaluation statements a nullable boolean will equate a null value with false -- it will not throw an error.

Methods: T GetValueOrDefault() & T GetValueOrDefault(T defaultValue)
Returns the stored value or the default value if the stored value is set to null.

Properties: HasValue & Value
Nullable types have two read only properties: HasValue and Value.

HasValue is a boolean property that returns true if Value != null. It provides a means to check your type for a non-null value before using it where you might throw an error:

 int? MyInt = null;
 int MyOtherInt;
 MyOtherInt = MyInt.Value + 1;    // Error! You can't add null + 1!!
 if (MyInt.HasValue) MyOtherInt = MyInt.Value + 1; // This is a better way.

Value returns the value of your type, null or otherwise.

int? MyInt = 27;
if (MyInt.HasValue) return MyInt.Value;  // returns 27.
MyInt = null;
return MyInt; // returns null.

Wrapping / Unwrapping

Wrapping is the process of packaging a value m from a non-nullable type N to a nullable type N? via the expression new N?(m)

Unwrapping is the process of evaluating a nullable type N? for instance m as type N or NULL and is performed via the 'Value' property (eg m.Value).

Note: Unwrapping a null instance generates the exception System.InvalidOperationException

The ?? Operator (aka the Null Coalescing Operator)

While not for use solely with Nullable types, the ?? operator proves very useful when you want to use a default value instead of a null value. The ?? operator returns the left operand of a statement if not null, otherwise it returns the right operand.

int? MyInt = null;
return MyInt ?? 27;  // returns 27, since MyInt is null

For more information see the blog entry by R. Aaron Zupancic on the ?? Operator

Using a user-defined value type
Building a value type
Using enumerations
Building an enumration
Using reference types

Reference types are more commonly referred to as objects. Classes, Interfaces and Delegates are all reference types, as well as the built-in reference types System.Object and System.String. Reference types are stored in managed Heap memory.

Unlike Value types, reference types can be assigned the value null.

Copying a reference type copies a reference that points to the object, not a copy of the object itself. This can seem counter-intuitive at times, since changing a copy of a reference will also change the original.

A Value type stores the value it is assigned, plain and simple - but a Reference type stores a pointer to a location in memory (on the heap). Think of the heap as a bunch of lockers and the Reference type holds the locker number (there are no locks in this metaphor). Copying a Reference type is like giving someone a copy of your locker number, rather than a copy of its contents. Two Reference types that point to the same memory is like two people sharing the same locker - both can modify its content:

Example of using Reference types

public class Dog
{
  private string breed;
  public string Breed { get {return breed;} set {breed = value;} }
  
  private int age;
  public int Age { get {return age;} set {age = value;} }
  
  public override string ToString()
  {
    return String.Format("is a {0} that is {1} years old.", Breed, Age);
  }
  
  public Dog(string dogBreed, int dogAge)
  {
    this.breed = dogBreed;
    this.age = dogAge;
  }
}

public class Example()
{
   public static void Main()
   {
     Dog myDog = new Dog("Labrador", 1);    // myDog points to a position in memory.
     Dog yourDog = new Dog("Doberman", 3);  // yourDog points to a different position in memory.

     yourDog = myDog; // both now point to the same position in memory, 
                    // where a Dog type has values of "Labrador" and 1
   
     yourDog.Breed = "Mutt";
     myDog.Age = 13; 

     Console.WriteLine("Your dog {0}\nMy dog {1}", yourDog.ToString(), myDog.ToString());
   }
}

Since the yourDog variable and the the myDog variable both point to the same memory store, the ouput of which would be:

Your dog is a Mutt that is 13 years old.
My dog is a Mutt that is 13 years old.
Using and building arrays
Using classes
Building a custom class
Using interfaces
Building a custom interface
Using attributes
Using generic types

The use of the four major categories of System Generic Types will be done elsewhere:

  • The nullable type was discussed above
  • A whole section follows on Generic collections
  • The generic event handler will be discussed in the Event / Delegate section.
  • The generic delegates will also be discussed in the Event / Delegate section as well as in the Generic collections section (Comparer class).
Building a generic type

The programming of a custom generic collection was shown in the article mentioned in the topics discussion.


Clipboard

To do:
could be fun to have an example of a custom generic type that is not related to arrays or collections


Exception classes

Some links to MSDN:

  • Exceptions and exception handling - MSDN
  • Handling and throwing exceptions - MSDN
  • Exception Hierarchy - MSDN
  • Exception Class and Properties - MSDN
Boxing and unboxing

See MSDN

All types derive diretly or indirectly from System.Object (including value types by the way of System.ValueType). This allows the very convenient concept of a reference to "any" object but poses some technical concerns because value types are not "referenced". Comes boxing and unboxing.

Boxing and unboxing enable value types to be treated as objects. Boxing a value type packages it inside an instance of the Object reference type. This allows the value type to be stored on the garbage collected heap. Unboxing extracts the value type from the object. In this example, the integer variable i is boxed and assigned to object o:

int i = 123;
object o = (object) i;  // boxing

Please also note that it is not necessary to explicitly cast an integer to an object (as shown in the example above) to cause the integer to be boxed. Invoking any of its methods would also cause it to be boxed on the heap:

int i=123;
String s=i.toString(); //This call will cause boxing

There is also a third way in which a value type can be boxed. That happens when you pass a value type as a parameter to a function that expects an object. Let's say there is a function prototyped as:

void aFunction(value as Object)

Now let's say from some other part of your program you call this function like this:

int i=123;
aFunction(i); //i is automatically boxed

This call would automatically cast the integer to an object, thus resulting in boxing.

The object o can then be unboxed and assigned to integer variable i:

o = 123;
i = (int) o;  // unboxing

Performance of boxing and unboxing

In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, an entirely new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally.

TypeForwardedToAttribute Class

See MSDN

For a discussion of TypeForwardToAttribute in the CLR see MSDN
Other possible links: Marcus' Blog, NotGartner

Using Collections

Exam objective: Manage a group of associated data in a .NET Framework application by using collections.

(Refer System.Collections namespace - MSDN)

ArrayList class

see MSDN

The ArrayList class is used for arrays whose size will dynamically increase as required. An ArrayList is not necessarily sorted.

using System;
using System.Collections;

public class Demo {
    public static void Main() {
        ArrayList myArrayList = new ArrayList();
        myArrayList.Add("Testing");
        myArrayList.Add("1...2...3");
    }
}
Collection interfaces
ICollection interface and IList interface
IComparer interface, IEqualityComparer interface, and IKeyComparer interface
IComparer interface - MSDN
IEqualityComparer interface - MSDN
IKeyComparer interface - IKeyComparer does not exist in .Net 2.0
IDictionary interface and IDictionaryEnumerator interface
IDictionary interface - MSDN
IDictionaryEnumerator interface - MSDN
IEnumerable interface and IEnumerator interface
IHashCodeProvider interface - MSDN - Interface is now obsolete (as of .NET 2.0)

Iterators

Hashtable class - MSDN

Used to represent a collection of key/value pairs.

CollectionBase class and ReadOnlyCollectionBase class

CollectionBase class - MSDN
ReadOnlyCollectionBase class -MSDN

DictionaryBase class and DictionaryEntry class

DictionaryBase class - MSDN
DictionaryEntry structure - MSDN

Comparer class - MSDN

Queue class - MSDN

SortedList class - MSDN

BitArray class - MSDN

Stack class - MSDN

Generic collections

Exam objective: Improve type safety and application performance in a .NET Framework application by using generic collections.

(Refer System.Collections.Generic namespace MSDN )

Collection.Generic interfaces

see also ONDotnet
Generic IComparable interface - MSND
(Refer System Namespace)
Generic ICollection interface and Generic IList interface
Generic ICollection interface - MSDN
Generic IList interface - MSDN
Generic IComparer interface and Generic IEqualityComparer interface
Generic IComparer interface - MSDN
Generic IEqualityComparer interface - MSDN
Generic IDictionary interface - MSDN
Generic IEnumerable interface and Generic IEnumerator interface
Generic IEnumerable interface - MSDN
Generic IEnumerator interface - MSDN
IHashCodeProvider interface - MSDN - Interface is now obsolete (as of .NET 2.0)

Generic Dictionary

Generic Dictionary class and Generic Dictionary.Enumerator structure
Generic Dictionary class - MSDN
Generic Dictionary.Enumerator structure - MSDN
Generic Dictionary.KeyCollection class and Dictionary.KeyCollection.Enumerator structure
Generic Dictionary.KeyCollection class - MSDN
Dictionary.KeyCollection.Enumerator structure - MSDN
Generic Dictionary.ValueCollection class and Dictionary.ValueCollection.Enumerator structure
Generic Dictionary.ValueCollection class - MSDN]
Dictionary.ValueCollection.Enumerator structure - MSDN]

Generic Comparer class and Generic EqualityComparer class

Generic Comparer class - MSDN
Generic EqualityComparer class - MSDN

Generic KeyValuePair structure - MSDN

Generic List class, Generic List.Enumerator structure, and Generic SortedList class

Generic List class - MSDN
A generic list class instance is simply declared using the List<T> syntax where T is the specific type.
Generic List.Enumerator structure - MSDN
Generic SortedList class - MSDN

Generic Queue class and Generic Queue.Enumerator structure

Generic Queue class - MSDN
Generic Queue.Enumerator structure - MSDN

Generic SortedDictionary class - MSDN

For differences between SortedList and SortedDictionary are explained see MSDN

Generic LinkedList

A Generic Linked List represents a doubly linked list and is a general-purpose linked list. It supports enumerators and implements the ICollection interface, consistent with other classes in the .NET Framework.
Generic LinkedList class - MSDN
Generic LinkedList.Enumerator structure - MSDN
Generic LinkedListNode class - MSDN

Generic Stack class and Generic Stack.Enumerator structure

Generic Stack class - MSDN
Generic Stack.Enumerator structure - MSDN

Specialized collections

Exam objective: Manage data in a .NET Framework application by using specialized collections.

(Refer System.Collections.Specialized namespace)

Specialized String classes
StringCollection class - MSDN
StringDictionary class - MSDN
StringEnumerator class - MSDN
Specialized Dictionary classes
HybridDictionary class - MSDN
IOrderedDictionary interface and OrderedDictionary class
IOrderedDictionary Interface - MSDN
OrderedDictionary class - MSDN
ListDictionary class - MSDN
Named collections
NameObjectCollectionBase class - MSDN
NameObjectCollectionBase.KeysCollection class - MSDN
NameValueCollection class - MSDN
CollectionsUtil class

CollectionsUtil class - MSDN

BitVector32 structure and BitVector32.Section structure
BitVector32 structure - MSDN
BitVector32.Section structure - MSDN

Standard interfaces

Exam objective: Implement .NET Framework interfaces to cause components to comply with standard contracts.

(Refer System namespace)

IComparable interface - MSDN

The IComparable interface defines a comparison method that a value type or class implements to create a type-specific comparison method

IDisposable interface - MSDN

The IDispose interface can be used to explicitly release unmanaged resources in custom classes. The consumer of an object can call this method when the object is no longer needed.
The .Net garbage collector releases memory allocated to managed objects when they are no longer used, however, it is not possible to predict when garbage collection will occur and it has no knowledge of unmanaged resources such as window handles, or open files and streams.

IConvertible interface - MSDN

ICloneable interface - MSDN

INullableValue interface - MSDN

IEquatable interface - MSDN

IFormattable interface - MSDN

Events and delegates

Exam objectives: Control interactions between .NET Framework application components by using events and delegates.

(Refer System namespace)

Delegate class

EventArgs class - MSDN

EventHandler delegates - MSDN


Previous / Next