Net framework session01

33
In this session, you will learn to: Explain the purpose of base system types Implement generics, Nullable types, exception classes, and attributes Implement comparison interfaces and the IConvertible, ICloneable, IFormattable, and IDisposable interfaces Objectives

Transcript of Net framework session01

Page 1: Net framework session01

In this session, you will learn to:

Explain the purpose of base system types

Implement generics, Nullable types, exception classes, and

attributes

Implement comparison interfaces and the IConvertible,

ICloneable, IFormattable, and IDisposable interfaces

Objectives

Page 2: Net framework session01

What are System Types?

System types are pre-defined data types.

Based on how compilers manage data types, software

development environments can be classified into two types:

Loosely typed

Strongly typed

.NET Framework provides a common set of data types called

Common Type System (CTS).

Examining Primary System Types

Strongly typed

environment

Page 3: Net framework session01

What are Value Types?

Value types are types that contain the actual data assigned to

them instead of a reference to the data.

There are two types of value types:

Built-in types: These are also referred to as simple or primitive

value types. Some of the built-in types are:

System.Char

System.Int32

System.Single

User-defined value types: These are custom value types that make

the .NET Framework fully extensible. Some of the user-defined

value types are:

Structure

Constant

Enumeration

Examining Primary System Types (Contd.)

Page 4: Net framework session01

What are Reference Types?

Reference types are system types that contain a reference to

assigned data instead of the actual data.

The data of a reference type is stored on a heap, but its

reference is stored on a stack.

There are two types of reference types:

Classes

Interfaces

Stack

A=“Hi” HiA

Heap

Examining Primary System Types (Contd.)

Page 5: Net framework session01

What is Boxing and Unboxing?

Boxing: It is the conversion of a value type to a reference type.

Unboxing: It is the explicit conversion of a reference type to a

value type.

Boxing

Unboxing

Value TypeReference

Type

Examining Primary System Types (Contd.)

Page 6: Net framework session01

The following code example implements boxing:

int a = 100;

object o = a;

a = 200;

Console.WriteLine("The value-type value = {0}",

a);

Console.WriteLine("The object-type value = {0}",

o);

Examining Primary System Types (Contd.)

Page 7: Net framework session01

The following code example implements unboxing:int a = 1;

Object o = a;

a = 100;

Console.WriteLine(a);

a = (int) o;

Console.WriteLine(a);

Examining Primary System Types (Contd.)

Page 8: Net framework session01

What is Casting?

Data type conversion in the .NET Framework is

known as type casting.

Type casting is of two types:

Implicit: Implicit casting is also called widening conversion because

narrow data types are converted to wide data types.

Explicit: Explicit casting is also called narrowing conversion

because wide data types are converted to narrow data types.

Single Double

Implicit casting

Explicit casting

Examining Primary System Types (Contd.)

Page 9: Net framework session01

The following code example shows the implementation of

implicit casting:

Int32 a;

Double b;

a = 100;

b = a;

The following code example shows the implementation of

explicit casting:

Int64 a = 100;

Int32 b = 0;

b = (Int32) a;

Examining Primary System Types (Contd.)

Page 10: Net framework session01

What is type safety?

Just a minute

Answer

Type safety is a situation where a compiler allows only those

values that comply with the assigned data type to be stored in

the variable.

Page 11: Net framework session01

What are Generics?

Generics are used to create type-safe collections for both

reference and value types.

By using generic types, you can create a method, class,

structure, or an interface in your code without specifying any

fixed data type.

They provide advantages such as reusability, type safety and

performance.

Working with Special System Types

Page 12: Net framework session01

The following code snippet defines a generic class called CommonData:

class Program

{

static void Main(string[] args)

{

CommonData<string>name = new

CommonData<string>();

name.Value = ".NET Framework";

CommonData<float>version = new

CommonData<float>();

version.Value = 2.0F;

Console.WriteLine(name.Value);

Console.WriteLine(version.Value);

} }

Working with Special System Types (Contd.)

Page 13: Net framework session01

public class CommonData<T>

{

private T _data;

public T Value

{

get

{

return this._data;

}

set

{

this._data = value;

}

}

}

Working with Special System Types (Contd.)

Page 14: Net framework session01

Advantages of generics

Reusability: A single generic type definition can be used for

multiple scenarios in the same code, without any alterations.

Type safety: Generic data types provide better type safety,

especially in situations where collections are used.

Performance: Generic types perform better than normal

system types because they reduce the need for boxing, unboxing, and type casting the variables or objects.

Working with Special System Types (Contd.)

Page 15: Net framework session01

What are generics?

Just a minute

Answer

The .NET Framework 2.0 provides generics that you can use to

create type-safe collections for both reference and value types.

Page 16: Net framework session01

Assign Null Values to Value Types by Using Nullable

Data Types

By using a Nullable data type you can assign null values for

value type variables.

Nullable data types are expanded only at run time.

The following code snippet shows implementation of the Nullable data type for the field date of anniversary:

public Nullable<DateTime> Anniversary

{ get

{return this._mAnniversary;}

set

{if (this._married)

this._mAnniversary = value;

else

this._mAnniversary = null;

} }

Working with Special System Types (Contd.)

Page 17: Net framework session01

Can value types be assigned a null value, and what value

will they then hold?

Just a minute

Answer

Value types can be assigned a null value. However, when you

assign a null value to a value type variable, only its default value

is assigned to the value type variable. For example, in the case

of an integer value type variable, the default value assigned will

be zero.

Page 18: Net framework session01

Handle Exceptions in Applications by Using Exception

Classes

Exceptions are error conditions or unexpected behavior that a

program may encounter at run time.

.Net Framework 2.0 provides two types of exception handling:

Predefined exception handling

User-defined exception handling

The try, catch, and finally block is used to handle exceptions

The throw statement is used to explicitly signal the

occurrence of an exception during program execution.

The exceptions are derived from the System.Exception

class for handling exceptions in the .Net Framework.

Working with Special System Types (Contd.)

Page 19: Net framework session01

The following code example uses a try/catch block to

catch a possible predefined exception: ArgumentOutOfRangeException.

class ExceptionHandling

{

public static void Main()

{

int[] sourceIntArray={1,2,3};

int[] destinationIntArray={5,6,7,8};

try

{

Array.Copy(sourceIntArray,

destinationIntArray,-1);

}

Working with Special System Types (Contd.)

Page 20: Net framework session01

catch (ArgumentOutOfRangeException e)

{

Console.WriteLine("Argument Out

Of Range Exception: {0}",e);

}

finally

{

Console.WriteLine("Finally block

is always executed.");

}

}

}

Working with Special System Types (Contd.)

Page 21: Net framework session01

Customize Code Behavior by Using Attributes

Attributes are an extended way to document code.

Attributes are of two types:

Predefined attributes: The following code snippet shows declaration of System.ObsoleteAttribute:

public class ObsoleteAttributeExample

{

[Obsolete("This function is obsolete")]

public static int Subtract( int a, int b)

{

return (a-b);

}

public static void Main()

{

int result = Subtract(9,2);

}

}

Working with Special System Types (Contd.)

Page 22: Net framework session01

Custom attributes: The following code snippet defines a custom attribute class MaxLengthAttribute:

[AttributeUsage(AttributeTargets.Field)]

class MaxLengthAttribute : Attribute

{ private int _max;

public MaxLengthAttribute(int max)

{ this._max = max;}

public bool IsValidLength(string value)

{

if (value == null)

return true;

else

if (this._max <= value.Length)

return true;

else

return false;

}

}

Working with Special System Types (Contd.)

Page 23: Net framework session01

What are Interfaces?

An interface looks like a class, but has no implementation. It

only contains definitions of events, indexers, methods, and

properties.

The classes and structures provide an implementation for each

member declared in the interface.

The following code example shows how you can define an

interface named Ishape:

interface IShape

{

int Area();

}

Working with Interfaces

Page 24: Net framework session01

Does an interface contain implementation?

Just a minute

Answer

An interface looks like a class, but it has no implementation. It

only contains definitions of events, indexers, methods, and

properties.

Page 25: Net framework session01

Compare Reference Types by Using Comparison Interfaces

The .NET Framework provides comparison interfaces for

comparing reference types.

The two most common types of comparison interfaces are:

IComparable: It defines a generalized comparison method that a

value type or class implements to create a type-specific

comparison method.

IEquatable: This interface applies only to generics. This

interface provides a generalized method to perform an equality

check between two instances of the same type.

Working with Interfaces (Contd.)

Comparison Interface

Reference

type 2

Reference

type 1

Page 26: Net framework session01

Convert a Reference Type by Using the IConvertible

Interface

IConvertible interface can be used to convert an object to

one of the CLR types.

IConvertible interface converts the value of an instance of

the implementing type to the equivalent data type under CTS.

The following code snippet shows its implementation of IConvertible interface :

class Decision : IConvertible

{ bool _agree;

DateTime

IConvertible.ToDateTime(IFormatProvider

provider)

{throw new InvalidCastException("Cannot cast

to DateTime"); }

//... other IConvertible Methods

}

Working with Interfaces (Contd.)

Page 27: Net framework session01

Create a Copy of a Reference Type by Using the ICloneable Interface

The ICloneable interface is used to create a new instance of

an object with the same value as an existing instance.

.Net Framework supports two types of cloning:

Shallow Cloning: Involves copying an object without copying any

references.

Deep Cloning: Involves making a copy of an object and any

references to other objects.

Working with Interfaces (Contd.)

Page 28: Net framework session01

Format System Data to a String by Using the IFormattable Interface

The IFormattable interface can be used for formatting the

value of the current instance by using the specified format.

The interface defines the ToString method to implement the

same.

The System.Object class provides a default implementation

of the ToString method.

Working with Interfaces (Contd.)

Page 29: Net framework session01

Dispose Unmanaged Resources by Using the IDisposable Interface

A special component of the .Net Framework called the garbage

collector manages the release of object memory on the heap

automatically.

The garbage collector periodically looks for unused objects on

the heap and deallocates their memory.

In the .NET Framework, unmanaged resources can be released explicitly by implementing the IDisposable

interface.

Garbage CollectorMemory

Garbage

Collection

Working with Interfaces (Contd.)

Page 30: Net framework session01

The following code example shows the implementation of the IDisposable interface in a class named

CustomerDataAccess:

public class CustomerDataAccess : IDisposable

{

protected virtual void Dispose(bool

disposing)

{ if(disposing)

{

// call dispose on any objects referenced by this

object }

// release unmanaged resources

}

Working with Interfaces (Contd.)

Page 31: Net framework session01

public void Dispose()

{

this.Dispose(true);

GC.SuppressFinalize(this);

}

~CustomerDataAccess()

{

this.Dispose(false);

}

}

Working with Interfaces (Contd.)

Page 32: Net framework session01

What is garbage collection?

Just a minute

Answer

Garbage collection is a form of automatic memory management.

The garbage collector manages the allocation and release of

memory for your application.

Page 33: Net framework session01

In this session, you learned that:

Base system types represent a set of predefined data types.

Boxing and unboxing can be used for conversion between

value types and reference types.

Generic types are used to create a method, class, structure, or

an interface without specifying any fixed data type.

Nullable data type is used to assign null values for value

type variables.

Predefined exceptions that the CLR generates or a custom

exception class can be used to handle exceptions.

Attributes are used to customize code behavior at run time.

Interfaces are used to specify a set of properties that, on

implementation, perform a specific functionality.

The commonly used interfaces are IComparable,

IEquatable, IConvertible, ICloneable, and

IFormattable.

Summary