Data types .net

The Microsoft .NET Framework provides a robust system of primitive types to represent data. Data primitives exist for the representation of integer numbers, floating-point numbers, Boolean values, characters, and strings. The type system enforces type-safety, so that implicit casts only occur when no loss of data is possible. Explicit conversions can be performed in situations that might cause a loss of data. The .NET data types contain built-in functionality that performs a variety of type related conversions and tasks.

Data types are used to store and represent data in your application. The .NET Framework provides an extensive system of types that allow you to store, manipulate, and pass values between members of your application. The .NET languages are strongly typed.

This means that objects of one type cannot be freely exchanged with objects of a different type. All parameters in method and property calls must be of the appropriate type, or the call will fail. Implicit and explicit conversions allow you to convert data types when necessary. Such conversions are possible because all types in the .NET Framework derive from Object, the base type of all classes and structures.

The .NET Data Types

The .NET data types are the types you use to store your data. They are value types and can be broken down into subcategories: Integer types, Floating-point types, the Boolean type, and the Char type. Two built-in reference types that are an integral part of your application will also be discussed: the String type and the Object type.

Integer Types

The .NET Framework provides a variety of Integer types. Table 3.1 summarizes these types and lists their corresponding Microsoft Visual Basic .NET and Microsoft Visual C# types.

The System.Single type is appropriate for floating-point calculations that require a lower degree of precision. It provides seven significant digits of precision. For greater levels of precision, you can use the System.Double type. This provides a much greater level of precision as well as the ability to handle vastly larger values. The System.Decimal type is specifically designed to facilitate financial calculations and is an ultra-high precision variable. Although it cannot hold values as great as System.Double, it has a much higher level of precision, providing 28 significant digits.

Non-Numeric Types

Four additional types that do not represent numbers are discussed in this section: System.Boolean, System.Char, System.String, and System.Object.

System.Boolean

The System.Boolean type is used to represent a value that is either true or false. It is called Boolean in Visual Basic .NET, and bool in Visual C#. The values that are valid for Boolean variables are True and False (Visual Basic .NET) or true and false (Visual C#).

System.Char

The System.Char type represents a single instance of a 16-bit Unicode character. It is called char in Visual C# and Char in Visual Basic .NET.

System.String

The System.String type is a reference type, and it represents a series of Char data types. In everyday terms, a string can represent a word, a paragraph, a key value, or any other string of characters. In Visual Basic .NET this type is called String, and in Visual C# it is called string.

System.Object

The Object type is the supertype of all types in the .NET Framework. Every type, whether value type or reference type, derives from System.Object. In Visual Basic .NET it is called Object, and in Visual C# it is called object.

If an object of a particular type is stored in an Object variable, it must be explicitly converted back to that type to access any of its inherent functionality.

Converting Types

At times, you will need to convert data from one type to another. Data can be converted in two ways: implicitly, which means the conversion is performed automatically, and explicitly, which means you must specifically ask for the conversion to be performed.

Implicit Conversions

Implicit conversions between types are automatically performed whenever the conversion can be performed without the loss of data.

Using Data Type Functionality

All of the data types have some kind of built-in functionality. At the very least, they all support four methods:

  • Equals. Determines whether two instances are equal
  • GetHashCode. Serves as a hash function for a particular type
  • GetType. Returns the type object for the current instance
  • ToString. Returns a human-readable form of the object

Boxing

The secret is called boxing. Boxing is the implicit conversion of value types to reference types. All classes and types derive from Object, and each of these four methods is a method of the Object class. Because each class derives from Object, they can be implicitly converted to that type. When you call one of these methods, the run time creates a temporary reference for your stack and allows you to treat it as a reference type.

Unboxing is the conversion of a boxed variable back to a value type. To unbox a variable, you must perform an explicit cast on the object to convert it to the appropriate type. Only objects that have been boxed can be unboxed.

Data Type Member Methods

Data types also have other methods that do not derive from Object. These methods usually involve functionality specific to the type. In Chapter 2, you were introduced to some of the comparison functions of the Char data type. Although the sheer scope of these methods is too great to be adequately dealt with in this text, some of the more generally useful functions will be discussed.

Parse

All of the value data types implement a Parse method. Parse is used to create a numeric value from a string. The Parse method is extremely useful when developing user interfaces. Controls that accept user input, such as TextBox, do so in the form of a string. The Parse method can be used to convert that string to usable data. Note that if a string cannot be read as a numeric value, an error will result. In all implementations, Parse is a static (Shared) method, and must be called from the type object rather than from an instance.

To convert a string to a numeric data type

Call the Parse method of that data type on that method.

String Functions

String manipulations are keenly important for many applications—converting strings to display formats, for instance, or extracting substrings from existing strings. The String class exposes a variety of member methods for the manipulation of strings.

Microsfot dot net Input validations part 2

Form-Level Validation

Form-level validation is the process of validating all of the fields on a form at once. A central procedure is used to implement form-level validation and is usually called when the user is ready to proceed to another step. A more advanced method of form-level validation is implementing a form-level keyboard handler.

The following example demonstrates how to create a form-level validation method. The sample tests that all the text boxes on a form have received input when a button called btnValidate is pressed, and resets the focus to the first text box it encounters without input.

Form-Level Keyboard Handler

A keyboard handler is a somewhat more sophisticated technique for form-level validation. A centralized keyboard handler allows you to manage data input for all fields on a form. For example, you could create a method that enables command buttons only after appropriate input has been entered into each field, and performs specific actions with each keystroke.

The KeyPress, KeyDown, and KeyUp events are used to implement a form-level keyboard handler. If a form has no visible and enabled controls, it will automatically raise keyboard events. If there are any controls on the form, however, the form will not automatically raise these events. In order for the form to raise these events, the KeyPreview property of the form must be set to true. When set to true, the form will raise keystroke events before the control that has the focus. For example, assume that there is a KeyPress handler for the form, a KeyPress handler for a text box on that form, and that the KeyPreview property of the form is set to true. When a key is pressed, the form will raise the KeyPress event first, and the form's KeyPress event handler will execute first. When execution has completed, the text box's KeyPress event handler will execute.

Providing User Feedback

When invalid input is entered into a field, the user should be alerted and given an opportunity to correct the error. There are many ways to inform the user of an input error. If the error is obvious and self-explanatory, an audio cue can alert the user to the problem. In Visual Basic .NET, you can use the Beep method to produce an attention-getting sound.

Other ways to draw a user's attention to an error include changing the BackColor or ForeColor of a control. For example, a text box with invalid input might have its BackColor changed to red.

If more detailed messages are required, you can use the MessageBox.Show method. This method displays a small, modal dialog box that contains an informative message. Because it is displayed modally, it halts program execution and is impossible for the user to ignore. The following shows how to call the MessageBox.Show method, which includes an informative message.

The ErrorProvider Component

The ErrorProvider component provides an easy way to communicate validation errors to your users. The ErrorProvider allows you to set an error message for each control on your form when the input is not valid. When an error message is set, an icon indicating the error will appear next to the control, and the error message text will be shown as a Tool Tip when the mouse hovers over the affected control. The ErrorProvider component can be found in the Windows Forms tab of the Toolbox.

Displaying an Error

To cause an error condition to be displayed next to a control, you use the SetError method of the ErrorProvider component. The SetError method requires the name of the control to be set and the text to be provided.

You can also set an error at design time. In the Properties window, you will find that once you add an ErrorProvider control to your form, each control has a new property called Error on x where x is the name of the ErrorProvider. You can set this property to a value at design time in the Properties window. If a value is set for the error, the control will immediately show an error at run time.

Different properties of the ErrorProvider component affect how the information is displayed to the user. The Icon property controls which icon is displayed next to the control. You might want to have multiple error providers on a single form—one that reports errors and one that reports warnings. You could use different icons for each to provide visual cues to the user. Another property is the BlinkStyle property. This property determines whether or not the error icon blinks when displayed. The BlinkRate property determines how rapidly the icon blinks.

To create a validation handler that uses the ErrorProvider component

  1. Create your form and add an ErrorProvider component to your form.

    The ErrorProvider component appears in the component tray.

  2. Set the CausesValidation property of the control you want to provide errors for to true if it is not true already.
  3. In the event handler for that control's Validating event, test the value. If an error condition occurs, use the SetError method to set the error to be displayed. The following example demonstrates a validation handler for a text box named pswordTextBox and an erroR provider named myErrorProvider.
related post

Input validations part 1

In most applications, the user enters information for the application through the user interface. Data validation ensures that all data entered by a user falls within acceptable parameters before proceeding with program execution. For example, you might have a field where a user enters a zip code as part of an address.

Using validation, you could verify that the field contained five and only five characters, all of which were numeric, before proceeding. Validating user input reduces the chance of an input error and makes your application more robust.

You can choose between two different types of validation for user input: form-level validation and field-level validation. Form-level validation verifies data after the user has filled all of the fields. For example, a user might be directed to fill in a name, address, and phone number on a form and then click OK. With form-level validation, all of the fields on the form would be validated when the user clicked OK.

Field-level validation, on the other hand, verifies the data in each field as the field is filled in. For example, if a user fills in a field that holds a phone number, field-level validation could verify that the number contains a valid area code before moving to the next field. As each digit is entered, you could also use control events to verify that only numbers are entered.

Field-Level Validation:

You might want to validate data as it is entered into each field. Field-level validation gives the developer control over user input as it occurs. In this section, you will learn how to use control events to validate user input, and how to use some properties of the TextBox control to help restrict input to appropriate parameters.

Using TextBox Properties:

The most commonly used control for user input is the TextBox. Several properties of the TextBox control allow you to restrict the values of user input that they will accept. Some of these properties include

  • MaxLength
  • PasswordChar
  • ReadOnly
  • MultiLine

Setting the MaxLength Property:

The MaxLength property limits the number of characters that can be entered into a text box. If the user attempts to exceed the number returned by MaxLength, the text box will accept no further input, and the system beeps to alert the user. This property is useful for text boxes that always contain data of the same length, such as a zip code field.

Using the PasswordChar Property:

The PasswordChar property allows you to hide user input at run time. For example, if you set the PasswordChar property to an asterisk (*), the text box will display an asterisk for each character regardless of user input. This type of behavior is commonly seen in password login boxes.

Although the password character is most commonly an asterisk, you can set it to any valid character. Thus, you could display all semicolons or ampersands, for example. The value of the Text property will always be set to the value the user enters regardless of the password character.

Setting the ReadOnly Property:

The ReadOnly property determines whether a user can edit the value displayed in a text box. If ReadOnly is set to true, the text cannot be changed by user input. If ReadOnly is set to false, the user can edit the value normally.

Using the MultiLine Property:

The MultiLine property determines whether a text box can accept multiple lines. When set to true, the user can enter multiple lines in the text box, each separated by a carriage return. The individual lines are stored as an array of strings in the TextBox.Lines collection and can be accessed by their index.

Using Events in Field-Level Validation:

Field-level keyboard events allow you to immediately validate user input. Controls that can receive keyboard input raise three keyboard events. They are

  • KeyDown
  • KeyPress
  • KeyUp

KeyDown and KeyUp

The KeyDown and KeyUp events are raised when a key is pressed and a key is released, respectively. The control that has the focus raises the event. When these events are raised, they package information about which key or combination of keys has been pressed or released in an instance of KeyEventArgs, a class that describes the key combination pressed. A method that handles the KeyDown or KeyUp event must include a KeyEventArgs parameter in its signature.

The KeyUp and KeyDown events are most commonly used for determining if the Alt, Ctrl, or Shift key has been pressed. This information is exposed through properties in the KeyEventArgs reference that is passed to the handler.

The KeyEventArgs properties—Alt, Control, and Shift—are properties that return a Boolean value, which indicates whether or not those keys are down. A value of true is returned if the corresponding key is down, and false is returned if the key is up. The following example demonstrates a KeyUp event handler that checks whether the Alt key is pressed.

You can also use the KeyEventArgs.KeyCode property to examine the actual key that triggered the event. This property returns a Key value that represents the key that was pressed (in the case of a KeyDown event) or released (in the case of a KeyUp event).

When a user presses a key that has a corresponding ASCII value, the KeyPress event is raised. These keys include any alphabetic and numeric characters (alphanumeric a-z, A-Z, and 0-9) as well as some special keyboard characters, such as the Enter and Backspace keys. If a key or key combination does not produce an ASCII value, it will not raise the KeyPress event. Examples of keys that do not raise this event include Ctrl, Alt, and the function keys.

This event is most useful for intercepting keystrokes and evaluating them. When this event is raised, an instance of KeyPressEventArgs is passed as a parameter to the event handler. The KeyPressEventArgs.KeyChar property contains the ASCII character represented by the keystroke that raised the event. If you want to make sure that the key pressed is a numeric key, for example, you can evaluate the KeyChar property in your KeyPress event handler.

Validating Characters

The Char data type contains several Shared (static) methods that are useful for validating characters trapped by the KeyPress event. These methods include

  • Char.IsDigit
  • Char.IsLetter
  • Char.IsLetterOrDigit
  • Char.IsPunctuation
  • Char.IsLower
  • Char.IsUpper

Each of these methods evaluates a character and returns a Boolean value; they are fairly self-explanatory. The Char.IsDigit function returns true if a character is a numeric digit, false if it is not. The Char.IsLower function returns true if a character is a lowercase letter, false otherwise. The other methods behave similarly. The following example uses the Char.IsNumber method to test if the key pressed is a numeric key.

Handling the Focus

Focus is the ability of an object to receive user input through the mouse or keyboard. Although you can have several controls on your form, only one can have the focus at any given time. The control that has the focus is always on the active form of the application.

Every control implements the Focus method. This method sets the focus to the control that called it. The Focus method returns a Boolean value that indicates whether or not the control was successful in setting the focus. Controls that are disabled or invisible cannot receive the focus. You can determine if a control can receive the focus by checking the CanFocus property, which returns true if the control can receive the focus and false if the control cannot.

Focus events occur in the following order:

  1. Enter
  2. GotFocus
  3. Leave
  4. Validating
  5. Validated
  6. LostFocus

The Enter and Leave events are raised when the focus arrives at a control and when the focus leaves a control, respectively. GotFocus and LostFocus are raised when a control first obtains the focus and when the focus has been lost from the control, respectively. Although you can use these events for field-level validation, the Validating and Validated events are more suited to that task.

The Validating and Validated Events

The easiest way to validate data is to use the Validating event. The Validating event occurs before a control loses the focus. This event is raised only when the CausesValidation property of the control that is about to receive the focus is set to true. Thus, if you want to use the Validating event to validate data entered in your control, the CausesValidation of the next control in the tab order should be set to true. In order to use Validating events, the CausesValidation property of the control to be validated must also be set to true. By default, the CausesValidation property of all controls is set to true when controls are created at design time. Controls such as Help buttons are typically the only kind of controls that have CausesValidation set to false.

The Validating event allows you to perform sophisticated validation on your controls. You could, for example, implement an event handler that tested whether the value entered corresponded to a very specific format. Another possible use is an event handler that doesn't allow the focus to leave the control until a value has been entered.

The Validating event includes an instance of the CancelEventArgs class. This class contains a single property, Cancel. If the input in your control does not fall within required parameters, you can use the Cancel property within your event handler to cancel the Validating event and return the focus to the control.

The Validated event fires after a control has successfully been validated. You can use this event to perform any actions based upon the validated input.

The following example demonstrates a handler for the Validating event. This method requires an entry in TextBox1 before it will allow the focus to move to the next control.

Methods in .net frame work

You can add methods as members to your classes. Methods represent actions your class can take. Methods generally come in two varieties: those that return a value (functions in Visual Basic) and those that do not return a value (Subs in Visual Basic).

The following code shows an example of both kinds of methods:

Visual Basic .NET

Public Sub MySub()
MessageBox.Show("This is a non-value returning method")
End Sub

Public Function Add(ByVal first as Integer, ByVal second as _
Integer)
Dim Result as Integer
Result = first + second
End Function

Visual C# makes no distinction between methods that return a value and methods that do not. In either case, you must specify the return value type. If the method does not return a value, its return type is void. Here are examples of C# methods:

Visual C#

public void myVoidMethod()
{
MessageBox.Show("This method doesn't return a value");
}
public int Add(int first, int second)
{
int Result;
Result = first + second;
}

Calling Methods:

A method does not execute until it is called. You can call a method by referencing its method name along with any required parameters.

Visual Basic .NET

' This line calls the Rotate method, with two parameters
Rotate(45, "Degrees")

Visual C#

// This line calls the Rotate method, with two parameters
Rotate(45, "Degrees");

The Main method is a special case. It is called upon initiation of program execution. Destructors, another special case, are called by the run time just prior to the destruction of an object. Constructors, a third special case, are executed by an object during its initialization.

Method Variables:

Variables declared within methods are said to have method scope. This means that once the method completes execution, they are destroyed and their memory reclaimed. They are said to have gone out of scope.

Variables within smaller divisions of methods have even more limited scope. For example, variables declared within a For-Next (for) loop are accessible only within the loop.

Visual Basic allows you to create method variables that are not destroyed after a method finishes execution. These variables, called static method variables, persist in memory and retain their values through multiple executions of a method.

Although this variable persists in memory, it is still only available during execution of this method. You would use a static variable for a method that needed to keep track of how many times it had been called.

Parameters:

A method can take one or more parameters. A parameter is an argument that is passed to the method by the method that calls it. Parameters are enclosed in parentheses after the method name in the method declaration, and types must be specified for parameters.

This method requires two parameters. A String parameter, which is given the local name name, and a Byte parameter, which is given the local name age. These variables have scope only for the duration of the method and cannot be used after the method returns.

Parameters can be passed in two ways: by value or by reference. In the .NET Framework, parameters are passed by value by default. This means that whenever a parameter is supplied, a copy of the data contained in the variable is made and passed to the method.

Any changes made in the value passed to the method are not reflected in the original variable. Although it is the default setting, you can explicitly indicate that a variable be passed by value in Visual Basic with the ByVal keyword.

When parameters are passed by reference, on the other hand, a reference to the memory location where the variable resides is supplied instead of an actual value. Thus, every time the method performs a manipulation on that variable, the changes are reflected in the actual object. To pass a parameter by reference in Visual Basic .NET, you use the keyword ByRef. In Visual C#, the keyword ref is used.

If your parameter is a reference type, it makes no difference if the parameter is passed by value or by reference—the behavior will be the same. In both cases, any manipulations done on the parameter will be reflected in the object passed as a parameter.

Output Parameters:

In Visual C#, you can also use output parameters. This feature is not available in Visual Basic .NET. An output parameter is a parameter that is passed from a called method to the method that called it—that is, the reverse direction.

Output parameters are useful if you want a method to return more than a single value. An output parameter is specified by using the out keyword. Output parameters are always passed by reference and do not need to be initialized before use.

Optional Parameters:

In Visual Basic .NET, you are able to specify optional parameters for your methods. This feature is not available in Visual C#. You specify a parameter as optional using the Optional keyword. Optional parameters must be the last parameters in a method declaration, and you must supply default values for optional parameters.

Constructors and Destructors:

The constructor is the first method that is run when an instance of a type is created. In Visual Basic, the constructor is always Sub New. In Visual C#, it is a method with the same name as the class. You use a constructor to initialize class and structure data before use. Constructors can never return a value, and can be overridden to provide custom intitialization functionality . A constructor can also contain calls to other methods.

Similarly, a destructor is the last method run by a class. A destructor (known as a finalizer in Visual Basic) contains code to "clean up" when a class is destroyed. This might include decrementing counters or releasing resources. A finalizer in Visual Basic .NET is always Sub Finalize(), and a destructor in Visual C# is a method with the same name as the class preceded by a tilde (~).

related post

DAY 1 MICROSOFT DOT NET FRAME WORK

DAY 2 MICROSOFT DOT NET BASE CLASS LIBRARY

DAY 3 MICROSOFT DOT NET CLASSES AND STRECTURES

DAY 4 METHODS IN FRAME WORK

DAY 5 INPUT VALIDATIONS IN DOT NET PART ONE

DAY 6 INPUT VALIDATIONS IN DOT NET PART TWO

DAY 7 DATA TYPES IN DOT NET

DAY 8 DATA TYPES IN DOT NET PART TWO

DAY 9 IMPLEMENTING PROPERTIES IN DOT NET

DAY 10 DELEGATES AND EVENTS





Using Classes and Structures

Classes and structures represent the two principal user-defined types.

Classes are templates for objects. They describe the kind and amount of data that an object will contain, but they do not represent any particular instance of an object. A real-world example of a class might be "Car"—the abstract idea of what a car is.

You know that a car has an engine and four wheels, a color, a fuel efficiency, and a dozen other properties. Although the Car class would describe all of these properties as well as have descriptions of actions the car might perform (go forward, turn on windshield wipers, etc.), the class would not represent any particular car.

Your car, on the other hand, is an object. It has a specific color, a specific fuel efficiency, a specific kind of engine, and four specific wheels. A different car might have different values for each of these properties, but both would be recognizable as being an instance of the Car class.

Members:

Classes describe the properties and behaviors of the objects they represent through members. Members are methods, fields, properties, and events that belong to a particular class. Fields and properties represent the data about an object—the color of the car, its fuel efficiency, and whether it has an automatic or manual transmission, for example.

A method represents something the object can do, such as go forward or turn on headlights. An event represents something interesting that happens to the object, such as overheating or crash.

Creating Classes:

You create a new class by using the Class (Visual Basic .NET) or class (C#) keyword. For example:

Visual Basic .NET

Public Class Widget
' Class member implementation goes here
End Class

Visual C#

public class Widget
{
// Class member implementation goes here
}

In this example, you use the Class (class) keyword to create a user-defined class. Widget is the name of the class, and the Public keyword specifies the access level.

Creating Structures:

Creating structures is very similar to creating classes. You use the Structure (Visual Basic .NET) or struct (C#) keyword. For example:

Visual Basic .NET

Public Structure Vector
' Structure implementation goes here
End Structure

Visual C#

public struct Vector
{
// Structure implementation goes here
}

Adding Members:

In Visual Basic .NET, a class comprises everything between the Class keyword and the End Class keyword. In C#, a class comprises everything within the curly braces ({}). Structures are similar. Within the bounds of a class or structure, you add the members. The following example demonstrates adding a member field to your Widget class.

Visual Basic .NET

Public Class Widget
Public Integer Spin
End Class

Visual C#

public class Widget
{
public int Spin;
}

Your Widget class now contains a member variable called Spin. This variable has a Public access level and can contain an Integer (int) value.

Nested Types:

Types can also contain other types. These are called nested types. Using classes as an example, a nested class usually represents an object that the parent class might need to create and manipulate, but that an external object would never need to create independently. An abstract example might be a Wheel class.

A Wheel class might need to create and maintain a collection of Spoke objects internally, but outside users would probably never need to create a Spoke object independent of a wheel. A more concrete example might be an AccountManager class that controls all the interaction with Account objects. You might not want to allow Account objects to be created independently of the AccountManager class, thus making Account a nested class inside AccountManager.

This does not mean that outside objects can never instantiate objects based on nested classes—this depends on the access level of both the parent class and the nested class.

Visual Basic .NET

Public Class Widget
' Widget Class code goes here
Private Class Widgurt
' Widgurt class code goes here
End Class
End Class

Visual C#

public class Widget
{
// Widget class code goes here
private class Widgurt
{
// Widgurt class code goes here.
}
}

Instantiating User-Defined Types:

You declare and instantiate a user-defined type the same way that you declare and instantiate a .NET Frameworks type. For both value types (structures) and reference types (classes), you need to declare the variable as a variable of that type, and then create an instance of it with the New (new) keyword.

Classes vs. Structures:

On the surface, classes and structures (structs) appear to be very similar. Both can contain members such as fields and methods, both require a constructor to create a new instance of themselves, and like all types in the .NET Framework, both inherit from Object.

The key difference between classes and structures is that classes are reference types and structures are value types. On a low level, this means that the instance data for classes is allocated in a memory location called the heap, whereas the instance data for structures is allocated in a memory location called the stack. Access to the stack is designed to be light and fast, but storage of large amounts of data on the stack can impede overall application performance.

In practical terms, what this means is that structures are best used for smaller, lightweight objects that contain relatively little instance data, or for objects that do not persist for long. Classes are best used for larger objects that contain more instance data and are expected to exist in memory for extended periods.

RELATED POSTS

DAY 1 MICROSOFT DOT NET FRAME WORK

DAY 2 MICROSOFT DOT NET BASE CLASS LIBRARY

DAY 3 MICROSOFT DOT NET CLASSES AND STRECTURES

DAY 4 METHODS IN FRAME WORK

DAY 5 INPUT VALIDATIONS IN DOT NET PART ONE

DAY 6 INPUT VALIDATIONS IN DOT NET PART TWO

DAY 7 DATA TYPES IN DOT NET

DAY 8 DATA TYPES IN DOT NET PART TWO

DAY 9 IMPLEMENTING PROPERTIES IN DOT NET

DAY 10 DELEGATES AND EVENTS

The .NET Base Class Library

The .NET base class library is a collection of object-oriented types and interfaces that provide object models and services for many of the complex programming tasks you will face.

Most of the types presented by the .NET base class library are fully extensible, allowing you to build types that incorporate your own functionality into your managed code.

The .NET Framework base class library contains the base classes that provide many of the services and objects you need when writing your applications. The class library is organized into namespaces. A namespace is a logical grouping of types that perform related functions. For example, the System.Windows.Forms namespace contains all of the types that make up windows forms and the controls used in those forms.

Namespaces are logical groupings of related classes. The namespaces in the .NET base class library are organized hierarchically. The root of the .NET Framework is the System namespace. Other namespaces can be accessed with the . (period) operator. Typical namespace construction appears as follows:
  • System
  • System.Data
  • System.Data.SQLClient
Reference Types and Value Types :

Types in the .NET Framework come in two varieties: value types and reference types. The primary difference between value types and reference types has to do with the way variable data is accessed. To understand this difference, a little bit of background on memory dynamics is required.

Application data memory is divided into two primary components, the stack and the heap. The stack is an area of memory that is reserved by the application for execution of the program. The stack is analogous to a stack of dinner plates. Plates are put onto the stack on top of one another.

When a plate is removed from the stack, it is always the one that was put on most recently. So it is with program variables. When a function is called, all of the variables used by the function are pushed onto the stack.

If that function calls additional functions, it pushes additional variables onto the stack. When the most recently called function terminates, all of its variables go out of scope and are popped off of the stack. The memory occupied by those variables is then freed up, and program execution continues.

The heap, on the other hand, is a separate area of memory that is reserved for the creation of objects that can be reused. The common language run time manages allocation of heap memory for objects and controls the reclamation of memory from unused objects through garbage collection.

All of the data associated with a value type is allocated on the stack. When a variable of a value type goes out of scope, it is destroyed, and its memory is reclaimed. A variable of a reference type, on the other hand, exists in two memory locations. The actual object data is allocated on the heap.

A variable containing a pointer to that object is allocated on the stack. When that variable is called by a function, it returns the memory address for the object it refers to. When that variable goes out of scope, the reference to the object is destroyed, but the object itself is not.

If any other references to that object exist, the object remains intact. If the object is left without any references to it, it is subject to garbage collection .

Examples of value types include primitives, such as Integer (int), Boolean (bool), Char (char), and so on, as well as user-defined Structures (structs) and Enumerations (enums). Classes represent the majority of reference types. Other types that are reference types include interfaces, delegates, and arrays.

Using .NET Framework Types in Your Application:

When you begin writing an application, you automatically begin with a reference to the .NET Framework base class library. This means that your application is aware of the base class library and is able to create instances of the types represented by it.

Value Types:

In Visual Basic .NET, you use the Dim statement to create a variable that represents a value type. In C#, you create a variable by declaring its type and then the variable name. The following is an example:

Visual Basic .NET

Dim myInteger as Integer

Visual C#

int myInteger;

This line tells the run time to allocate the appropriate amount of memory to hold an integer variable. Although this creates the variable, it does not assign a value to it. You can assign a value using the assignment operator as follows:

Visual Basic .NET

myInteger = 42

Visual C#

myInteger = 42;

You can also choose to assign a value to a variable upon creation, as shown in this example:

Reference Types:

Creating an instance of a type is a two-step process. The first step is to declare the variable as that type. This allocates the appropriate amount of memory for that variable, but does not actually create the object. You use the following syntax to declare an object:

Visual Basic .NET

Dim myForm As System.Windows.Forms.Form

Visual C#

System.Windows.Forms.Form myForm;

The preceding line tells the run time to set aside enough memory to hold a Form variable and assigns it the name myForm, but does not actually create the Form object in memory. The second step, called instantiation, actually creates the object. An example of instantiation follows:

Visual Basic .NET

myForm = New System.Windows.Forms.Form()

Visual C#

myForm = new System.Windows.Forms.Form();

This line is actually making a call to the constructor method of the type System.Windows.Forms.Form by way of the New (new) keyword. The constructor is a special method that is invoked only at the beginning of an object's lifetime. It contains any code that must be executed in order for the object to work (assigning values to properties, for example).

If any parameters were required by the constructor, they would be contained within the parentheses at the end of the line. The following example shows declaration and instantiation of a hypothetical Widget class that requires a string as a parameter in the constructor.

Visual Basic .NET

Dim myWidget as WidgetmyWidget = New Widget("This string is required by the constructor")

Visual C#

Widget myWidget;myWidget = new Widget("This string is required by the constructor");
You can also combine both declaration and instantiation into a single statement, if desired. By declaring and instantiating an object in the same line, you reserve the memory for the object and immediately create the object that resides in that memory. Although there was a significant performance penalty for this shortcut in previous versions of Visual Basic, Visual Basic .NET and Visual C# are optimized to allow this behavior without any loss of performance. The following example shows the one-step declaration and instantiation of a new Form.

Visual Basic .NET

Dim myForm As New System.Windows.Forms.Form()

Visual C#

System.Windows.Forms.Form myForm = new System.Windows.Forms.Form();
Both value types and reference types must be initialized before use. For class and structure fields in Visual Basic .NET, types are initialized with default values upon declaration. Numeric value types such as Integer or the floating-point types are assigned zero, Boolean variables are assigned False, and reference types are assigned to a null reference.

In C#, variables are not given default initialization. Any attempt to use an uninitialized variable, whether at a class level or a method level, will result in an error.

Using Value Type and Reference Type Variables

A variable that represents a value type contains all of the data represented by that type. A variable that represents a reference type contains a reference to a particular object. This is an important distinction to make. Consider the following example:

Visual Basic .NET

Dim x, y Integer x = 15y = xx = 30' What is the value of y?

Visual C#

int x, y;x = 15;y = x;x = 30;// What is the value of y?

In this example, two integer variables named x and y are created. x is assigned a value of 15, then y is assigned the value of x. Next, the value of x is changed to 30, and the question is posed: what is the value of y? The answer to this question might seem obvious, and it is: y = 15.

This is because x and y are two separate variables and have no effect on each other when changed. When the line y = x is encountered, the value of x is copied to the value of y, and there is no further connection between the two variables.

This situation changes, however in the case of reference types. Let's reconsider the previous example using a reference type (Form) instead of a value type.

Visual Basic .NET

Dim x, y as System.Windows.Forms.Form x = New System.Windows.Forms.Form()x.Text = "This is Form 1"y = xx.Text = "This is Form 2"' What value does y.Text return?

Visual C#

System.Windows.Forms.Form x,y;x = new System.Windows.Forms.Form();x.Text = "This is Form 1";y = x;x.Text = "This is Form 2";// What value does y.Text return?
What value does y.Text return? This time, the answer is not as obvious. Because System.Windows.Forms.Form is a reference type, the variable x does not actually contain a Form; rather, it points to an instance of a Form.

When the line y = x is encountered, the run time copies the reference from variable x to y. Thus, the variable y now points to the same instance of Form as the variable x does. Because these two variables actually refer to the same instance of the object, they will return the same values for properties of that object. Thus, y.Text returns "This is Form 2".

The Imports and using Statements

Up to this point, if you wanted to access a type in the .NET Framework base class library, you had to use the full name of the type including every namespace it belongs to. For example:

System.Windows.Forms.Form

You can make your development environment "aware" of various namespaces by using the Imports (Visual Basic .NET) or using (Visual C#) statement. This allows you to refer to a type using only its generic name and allows you to omit the qualifying namespaces.

Thus, you could refer to System.Windows.Forms.Form as simply Form. In Visual Basic .NET, the Imports statement must be placed at the top of the code window, preceding any other statements (except for Option statements). In Visual C#, the using statement must occur before any other namespace element, such as a class or struct.This example demonstrates the usage of this statement:

Visual Basic .NET

Imports System.Windows.Forms

Visual C#

using System.Windows.Forms;

When two types of the same name exist in more than one imported namespace, you must again use the fully qualified name in order to avoid a naming conflict. Thus, if you are using MyNameSpaceOne and MyNameSpaceTwo, and each contains a Widget class, you would have to refer to MyNameSpaceOne.Widget or MyNameSpaceTwo.Widget to ensure the correct result.

In C#, you can resolve namespace conflicts such as these by creating an alias. An alias allows you to choose one name to refer to another class. You create an alias using the using keyword, as shown below.

Visual C#

using myAlias = MyNameSpaceTwo.Widget;
After implementing an alias, you can then use it in code to represent the aliased class.

For example:

Visual C#

// You can now refer to MyNameSpaceTwo as myAlias. The // following two lines produce the same result:MyNameSpaceTwo.Widget = new myNameSpaceTwo.Widget;MyAlias anotherWidget = new myAlias;
Aliasing is not available in Visual Basic .NET.

Referencing External Libraries:

You might want to use class libraries not contained by the frame work, such as libraries developed by third-party vendors or libraries you have developed. In order to access these libraries, you must create a reference to that class library.

To create a reference to an external library:

In the Solution Explorer, right-click the References node of your project.
From the pop-up menu, choose Add Reference. The Add Reference dialog box appears.
Choose the appropriate tab for the library you want to reference. .NET libraries are available on the .NET tab. Legacy COM libraries appear on the COM tab, and local Visual Studio projects appear on the Projects tab.

Locate the library you want to reference, and double-click it to add it to the Selected components box. Click OK to confirm the choice of that reference.

RELATED POSTS

DAY 1 MICROSOFT DOT NET FRAME WORK

DAY 2 MICROSOFT DOT NET BASE CLASS LIBRARY

DAY 3 MICROSOFT DOT NET CLASSES AND STRECTURES

DAY 4 METHODS IN FRAME WORK

DAY 5 INPUT VALIDATIONS IN DOT NET PART ONE

DAY 6 INPUT VALIDATIONS IN DOT NET PART TWO

DAY 7 DATA TYPES IN DOT NET

DAY 8 DATA TYPES IN DOT NET PART TWO

DAY 9 IMPLEMENTING PROPERTIES IN DOT NET

DAY 10 DELEGATES AND EVENTS

The .NET Framework and the Common Language Runtime

The Microsoft .NET Framework is an integrated and managed environment for the development and execution of your code.

Overview of the .NET Framework:

The .NET Framework is a managed, type-safe environment for application development and execution. The framework manages all aspects of the execution of your program: it allocates memory for the storage of data and instructions, grants or denies the appropriate permissions to your application, initiates and manages application execution, and manages the reallocation of memory for resources that are no longer needed. The .NET Framework consists of two main components: the common language runtime and the .NET Framework class library.

The common language runtime can be thought of as the environment that manages code execution. It provides core services, such as code compilation, memory allocation, thread management, and garbage collection. Through the common type system (CTS), it enforces strict type safety, and it ensures that code is executed in a safe environment by enforcing code access security.

The .NET Framework class library provides a collection of useful and reusable types that are designed to integrate with the common language runtime. The types provided by the .NET Framework are object-oriented and fully extensible, and allow you to seamlessly integrate your applications with the .NET Framework.

Languages and the .NET Framework:

The .NET Framework is designed for cross-language compatibility. Simply put, this means that .NET components can interact with each other no matter what language they were originally written in.

So, an application written in Microsoft Visual Basic .NET might reference a DLL file written in Microsoft C#, which in turn might access a resource written in managed Microsoft C++ or any other .NET language. This language interoperability extends to full object-oriented inheritance. A Visual Basic .NET class might be derived from a C# class, for example, or vice versa.

This level of cross-language compatibility is possible because of the common language run time. When a .NET application is compiled, it is converted from the language it was written in (Visual Basic .NET, C#, or any other .NET compliant language) to Microsoft Intermediate Language (MSIL or IL).

This is a low-level language designed to be read and understood by the common language run time. Because all .NET executables and DLLs exist as intermediate language, they can freely interoperate. The Common Language Specification defines the minimum standards that .NET language compilers must conform to, and thus ensures that any source code compiled by a .NET compiler can interoperate with the .NET Framework.

The CTS ensures type compatibility between .NET components. Because .NET applications are converted to IL prior to deployment and execution, all primitive data types are represented as .NET types. Thus, a Visual Basic Integer and a C# int are both represented in IL code as a System.Int32.

Because both languages use a common and interconvertable type system, it is possible to transfer data between components and avoid time-consuming conversions or hard-to-find errors.

Visual Studio .NET ships with with such languages as Visual Basic .NET, Visual C#, and Visual C++ with managed extensions as well as the JScript scripting language. You can also write managed code for the .NET Framework in other languages. Third party compilers exist for Fortran .NET, Cobol .NET, Perl .Net, and a host of other languages. All of these languages share the same cross-language compatibility and inheritability.

Thus you can write code for the .NET Framework in the language of your choice, and it will be able to interact with code written for the .NET Framework in any other language.

The Structure of a .NET Application:

To understand how the common language run time manages the execution of code, you must examine the structure of a .NET application. The primary unit of a .NET application is the assembly. An assembly is a self-describing collection of code, resources, and metadata.

The assembly manifest contains information about what is contained within the assembly. The assembly manifest provides

  1. Identity information, such as the name and version number of the assembly.
  2. A list of all types exposed by the assembly.
  3. A list of other assemblies required by the assembly.

A list of code access security instructions for the assembly. This includes a list of permissions required by the assembly and permissions to be denied the assembly.

Each assembly has one and only one assembly manifest, and it contains all the description information for the assembly. The assembly manifest can be contained in its own separate file, or it can be contained within one of the assembly's modules.

An assembly also contains one or more modules. A module contains the code that makes up your application or library, and metadata that describes that code. When you compile a project into an assembly, your code is converted from high-level code to IL. Because all managed code is first converted to IL code, applications written in different languages can easily interact.

For example, one developer might write an application in Visual C# that accesses a DLL in Visual Basic .NET. Both resources will be converted to IL modules before being executed, thus avoiding any language incompatibility issues.

Each module also contains a number of types. Types are templates that describe a set of data encapsulation and functionality. There are two kinds of types: reference types (classes) and value types (structures).

Each type is described to the common language run time in the assembly manifest. A type can contain fields, properties, and methods, each of which should be related to a common functionality. For example, you might have a class that represents a bank account.

It would contain fields, properties, and methods related to the functions needed to implement a bank account. A field represents storage of a particular type of data. You might have a field that stores the name of an account holder.

Properties are similar to fields, but usually provide some kind of validation when the data is set or retrieved. You might have a property that represents the balance available in an account. When an attempt is made to change the value, the property could check to see if the attempted change was greater than a predetermined limit, and if so, could disallow the change.

Methods represent behavior, such as actions taken on data stored within the class or changes to the user interface. Continuing with the bank account example, you might have a Transfer method that transfers a balance from a checking account to a savings account, or an Alert method that warns the user when his balance has fallen below a predetermined level.

Compilation and Execution of a .NET Application:

When you compile a .NET application, it is not compiled to binary machine code; rather, it is converted to IL, which is a low-level set of instructions understood by the common language run time.

This is the form that your deployed application takes—one or more assemblies consisting of executable files and DLL files in IL form. At least one of these assemblies will contain an executable file that has been designated as the entry point for the application.

When execution of your program begins, the first assembly is loaded into memory. At this point, the common language run time examines the assembly manifest and determines the requirements to run the program. It examines security permissions requested by the assembly and compares them to the system's security policy.

If the system's security policy does not allow the requested permissions, the application will not be run. If the application passes the system's security policy, the common language run time executes the code. It creates a process for the application to run in and begins application execution. When execution starts, the first bit of code that needs to be executed is loaded into memory and compiled into native binary code from IL by the common language run time's Just-In-Time (JIT) compiler.

Once compiled, the code is executed and stored in memory as native code, so each portion of code is compiled only once during the execution of an application. Whenever program execution branches to code that has not yet been executed, the JIT compiler compiles it ahead of execution and stores it in memory as binary code.

This way, application performance is maximized because only the parts of a program that are executed are compiled.

Summary :

The .NET Framework is a foundation for software development. The .NET Framework consists of the common language run time, which provides many of the core services required for program execution, and the .NET base class library, which exposes a set of predeveloped classes to facilitate program development. The Common Language Specification defines a minimum set of standards that all languages using the .NET Framework must support, and the CTS ensures type compatibility between components developed in different languages.

The primary unit of a .NET application is the assembly, which consists of an assembly manifest. The assembly manifest describes the assembly and one or more modules, which contain the source code for the application.

A .NET executable is stored as an IL file. When loaded, the assembly is checked against the security policy of the local system. If it is allowed to run, the first assembly is loaded into memory and JIT compiled into native binary code where it is stored for the remainder of the program's execution.

RELATED POST

DAY 1 MICROSOFT DOT NET FRAME WORK

DAY 2 MICROSOFT DOT NET BASE CLASS LIBRARY

DAY 3 MICROSOFT DOT NET CLASSES AND STRECTURES

DAY 4 METHODS IN FRAME WORK

DAY 5 INPUT VALIDATIONS IN DOT NET PART ONE

DAY 6 INPUT VALIDATIONS IN DOT NET PART TWO

DAY 7 DATA TYPES IN DOT NET

DAY 8 DATA TYPES IN DOT NET PART TWO

DAY 9 IMPLEMENTING PROPERTIES IN DOT NET

DAY 10 DELEGATES AND EVENTS