Vous êtes sur la page 1sur 84

C# 2.

0 enhancement
Generics
Anonymous methods
Nullable Types
Iterators
Partial types
Generics
Generics

Permit classes, structs, interfaces, delegates, and


methods to be parameterized by the types of data they
store and manipulate.

Generics are useful because they provide stronger


compile-time type checking, require fewer explicit
conversions between data types, and reduce the need
for boxing operations and run-time type checks.
To Understand Generics

Understand Value v/s Reference type.

Boxing & Un boxing

Why need Strong Type

Generic (as Management jargon)


Generics
First we have to Understanding Value types & Reference Types
- .net Data type may be Value based or Reference based

Valued Based:
- Value based Data types includes (numeric data types like float, int, etc.)
and enumerations and structures. And are allocated on the stack.

- Value based types could be quickly remove from the Stack / memory once
they fall out from the defining scope…
public void m()
{
int x=0;
console.writeline(x);
………..// x will pop out from the stack ..
}
Valued based v/s Referenced based type
Valued Based:
- Member to member copy is achieved on assigning one value type to
another.
public void m()
{
int x=20;
int y=x;
// now if I make j=200;
x= 20; (It will stay same)
}

- Struct are always Value types:


Struct Myname
{
public int x, y;
}
to call it I will use – Myname ob = new Myname();
Valued based v/s Referenced based type

Referenced Based Type:

- Referenced based type are allocated on Managed Heap.

- .Net Garbage collector destroy them. Till them they stay in the
memory.

- Assignment of reference type results in a new reference to the same


object on the heap.
Valued based v/s Referenced based type

Demo

(console application D:\prabhjot\hcl)


Valued based v/s Referenced based type
Valued based v/s Referenced based type
Valued based v/s Referenced based type
Valued based v/s Referenced based type
Valued based v/s Referenced based type

la ss
it hc
e w
c tur
u
str
lace
p
Re
Pitch for Boxing & Unboxing

Looking at the old example we realize that the behaviors of value


based and reference based are so different

Over everything: what if?

We may occasionally needs to represent a variable of one


category as the variable of another category.
Boxing
- To convert Value type to Reference type c# provides Boxing
mechanism.
Short s =25;
// to box the value
object ob= s;

A process of explicitly converting the value type into corresponding


reference type by storing the variable in a System.Object.

CLR works in the back ground and allocate a new object on the heap
plus assign the value(here 25).
& Unboxing
- To convert Reference type to Value type c# provides UNBoxing
mechanism.

Short y= (short)ob;

It is must or mandatory that you unbox into an Appropriate data type.

Else you will get a INVALIDCASTEXCEPTION.


& Unboxing

Demo

(D:\prabhjot\hcldemo2\hcldemo2)
& Unboxing

ers
ra mm
o g
pr
f or
blem
o
Pr
Automatic Unboxing

Demo

Console application : D:\prabhjot\hclcsharpdemo3\hclcsharpdemo3


Automatic Unboxing
Automatic boxing

• When working with System.Collections (Arraylist


provides you members that allows to insert obtain and
remove items)
Automatic boxing

C # Automatically boxes variables when appropriate. (passing a value type into


a method requiring an Object parameter).

Static void main(string[] args)


{
// create a int (value type)
Int myInt =99;
Use(myInt)
}
Static void Use(Oblect o)
{
console.writeline(“value {0}, o”);
}
Unboxing with Custom Value type (No automatic)

• When you pass custom Struct or enumeration into a


method which takes Object as parameter
Generics
Generics

• In Reality- The unboxing process is very helpful in that it


allows everything can be treated as s System.Object type,
while CLR takes care of memory related details on our behalf.

So far Out come:

• Boxing and Unboxing takes some Processing Time. It hurts


the Performance of the Application. So is Very Expensive.
(Performance loss with Arraylist)
• Unbxing is Must But needs to be with proper data type else
run time error. (Programmer pain)
Generics
• This simplified Approach came with a burden of box-
unbox-box process as a result reflects two weakness:

- Performance loss (With Array List)

- Lack of type safety


(At runtime will know that you have used wrong data type for
casting)
Generics

• When using System.Collections.Generic.List<>, Boxing


and unboxing is not required.

Demo

D:\prabhjot\windows\hcldcsharpdemo4
Generics
Generics
Generics

• When using System.Collections.Generic.List<>, Boxing


and unboxing is not required.

• Generics Provides a way for programmer to define


“place holder”, formally called typed parameter.

• We can build our own generic method, classes,


structures, interfaces and delegates.
Generics

• Generics Provides a way for programmer to define


“place holder”, formally called typed parameter.

• We can build our own generic method, classes,


structures, interfaces and delegates.

Demo

Console Application D:\prabhjot\hcalcsharpdemogm5


Generics
Generics
Generics
Generics

• We can build our own generic method, classes,


structures, Base Class, Custom Generic
collections, interfaces and delegates.

Demo

D:\prabhjot\hclcsharpdemo6gc
Generics
Generics
Generics
Generic Base Class
Generic Interface
Generic Delegates
Generic Lacks Operator Supports
C# Nullable Types
C# Nullable Types

A Nullable type supports all values of its underlying type


plus an additional null state.

Thus if we declare Nullable System.Boolean, it could be


assigned a value from the set {true, false, null}.
C# Nullable Types
Static void Main (string[] args)
{ // compile error
bool myBool = null;
int myint= Null;
}

Static void Main (string[] args)


{ // define some local nullable type
bool? nullablemyBool = null;
int? nullablemyint= Null;
Int? nullableinttwo=30;
int? arrayof nullableInts= new int?[10];
}
C# Nullable Types
Static void Main (string[] args)
{ int? i= dr.GetIntFromDatabase();
if(i.HasVAlue)
{
}
else
{console.writeline (“sorry”); }
}

Static void Main (string[] args)


{ // define some local nullable type
bool? nullablemyBool = null;
int? nullablemyint= Null;
Int? nullableinttwo=30;
int? arrayof nullableInts= new int?[10];
}
C# Nullable Types

To define a Nullable variable type, the question mark symbol(?), is


suffixed to the under lying Datatype.

This syntax is only legal with value type or value of array types. Any
attempts to create a nullable reference type will issue a compile
error.

Local nullable variable must be assigned an initial value


C# Nullable Types
Can be particularly useful when you are interacting with databases, given
that columns in a data base may be intentionally empty.

Class Databasereader
{ //nullable Data field
public int? numbericValue;
public bool? boolValue=True;
//nullable return type

public int? GetintFromDatabse()


{return numbericValue;}
//nullable return type

public bool? GetBoolFromDatabase()


{return boolValue;}
}
Partial Types

Allow classes, structs, and interfaces to be broken into multiple pieces stored in
different source files for easier development and maintenance.

C# 2005 introduces a new type modifier named partial that allows you to define a C#
type across multiple *.cs files. Earlier version required all code for a given type to be
defined within a single *.cs file.

For example, using Partial class modifier, we could place all the public members in a
file named MyType_Public.cs and while the private fields into MyType_Private.cs file.

once these files are compile by csc.exe, forms a single unified type
Partial Types
partial classes mean that your class definition can be split into
multiple physical files. Logically, partial classes do not make
any difference to the compiler. During compile time, it simply
groups all the various partial classes and treats them as a
single entity.

Using partial classes, the UI code can be hidden from the


developer, who usually has no need to access it anyway.
Partial classes will also make debugging easier, as the code
is partitioned into separate files.
Here are some good reasons to use partial classes:
They allow programmers on your team to work on different parts of
a class without needing to share the same physical file.

• The most compelling reason for using partial class is to separate


your application business logic from the designer-generated code.
For example, the code generated by Visual Studio 2005 for a
Windows Form is kept separate from your business logic (we will
discuss this in a later section). This will prevent developers from
messing with the code that is used for the UI. At the same time, it
will prevent you from losing your changes to the designer-generated
code when you change the UI.
Partial Types

Demo

D:\prabhjot\PartialType
Partial Types
Partial Types
Partial Types
Anonymous methods

Allows code blocks to be written “in-line” where delegate


values are expected.
Anonymous methods

Lets Understand the Difference between old delegate and new proposed
Anonymous Delegate through Practical.

Lets start with normal delegate first……


Anonymous methods

ate
eleg
d
al
orm
N
Anonymous methods

In c# 2.0 this code will not have a name


Anonymous methods

So we used Anonymous Delegate


in place of Normal delegate. So we have a
Methods without a name, compiler will give it any
Anonymous methods

If the method will not be reused then use inline


Declaration i.e anonymous else not
Anonymous method
• For Closure we will use this.

• Anonymous delegate retain its scope at


the time they were instantiated.

• Lets create a methods that will return the


instance of our delegate
Anonymous method

It remembered Hello
Anonymous method-end
Iterators

As we all familiar about C# for-each , it allow to iterate over the elements


of a collection of enumerable ,the GetEnumerator method returns the
enumerator from the collection. If we look enumerator has certain
constraints like performance, implementations etc , Iterators makes this
task more simple and efficient
Iterators

Demo

D:\prabhjot\hclcsharpdemo6

D:\prabhjot\csharpdemo5
Without Iterators
Without Iterators
Without Iterators
Without Iterators
With Iterators
With Iterators
Iterators-end

Conclusion:

Vous aimerez peut-être aussi