Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
C# and .net framework
AGENDA
0 Introduction of C #
0 History of C #
0 Design Goals
0 Why C#? :Features
0 C # & Object-OrientedApproach
0 Advantages of C #
0 Applications of C #
0 Introduction to .Net Framework
0 History of .Net
0 Design Features
0 .Net Architecture
0 .Net & Object OrientedApproach
0 Application of . N E T :G U I
0 Wrapping Up
0 References
INTRODUCTIONTO C#
0 C # is a multi-paradigm programming language which is based on object-
oriented andcomponent-orientedprogrammingdisciplines.
0 It provides a framework for free intermixing constructs from different
paradigms.
0 It usesthe “besttool for the job”sincenooneparadigmsolvesallproblemsin
the mostefficientway.
BRIEFHISTORY
0 C# was developed by Microsoft with Anders Hejlsberg as the principal
designer and lead architect, within its . N E T initiative and it made its
appearance in2000.
0 Anders Hejlsberg and his team wanted to build a new programming language
that would help to write classlibraries in a . N E T framework. He claimedthat
C # wasmuchcloserto C++ initsdesign.
0 The name"C sharp"wasinspired by musicalnotation where a sharp indicates
that the writtennoteshouldbe madea semitonehigherinpitch.
0 Ever since its inception, C# hascontroversially been stated as an imitation of
Java. However, through the course of time, both Java and C # have exhibited
distinct features whichsupport strongobject-oriented designprinciples.
DESIGNGOALS
0 C # wasintended tobe a simple,modern,object-oriented language.
0 The language and implementation had to provide support for software
engineering principles like strong type checking, array bounds checking and
automaticgarbagecollection.
0 The language was intended for development of software components
suitable for deploymentindistributedenvironments.
0 Source code portability was importantfor programmerswhowere familiar
withC andC++.
0 Support for internalizationto adapt thesoftwareto different languages.
WHYC# ? : FEATURES
0 C # isthe first“component-oriented” languageinthe C / C + + family.
0 The big ideaof C # isthat everythingisanobject.
0 C # is a programming language that directly reflects the underlying Common Language
Infrastructure (CLI). Most of its intrinsic types correspond to value-types implemented by
the CLI framework.
0 Type-safety: C # is more type safe than C++. Type safety is the extent to which a
programminglanguagediscouragesor prevents typeerrors.
0 C#, likeC++, butunlikeJava, supportsoperator overloading.
0 Managed memory is automatically garbage collected. Garbage collection addresses the
problem of memory leaks by freeing the programmer of responsibility for releasing memory
that isnolongerneeded.
0 C # provides properties as syntactic sugar for a commonpattern in which a pair of methods,
accessor (getter) and mutator (setter) encapsulate operations on a single attribute of a
class.
WHYC# ? :FEATURES…cont.
0 In addition to the try...catch construct to handle exceptions, C# has a
try...finally construct to guarantee execution of the code in the finallyblock,
whetheranexceptionoccursornot.
0 Unlike Java, C # does not have checked exceptions. This has been a
consciousdecisionbased onthe issuesof scalabilityandversionability.
0 Multiple inheritance is not supported, although a class can implement any
number of interfaces. This was a design decision to avoid complication and
simplifyarchitecturalrequirementsthroughoutCLI.
0 C # supports a strict Boolean data type, bool. Statements that take
conditions, such as while and if, require an expression of a type that
implementsthe true operator, suchastheboolean type.
C# &OBJECTORIENTEDAPPROACH
(I) Structs &Classes
(II) Interfaces
(III) Delegates
(IV) Switch Statement: FallThrough
(V) For Each: Control Flow
(VI)Virtual Methods
(VII) Boxing &Unboxing
(VIII) CommonType System
(IX) Generics
(X) Reflection
(I) STRUCTS&CLASSES INC#
0 In C# structs are very different from classes. Structs in C# are designed to
encapsulate lightweight objects. They are value types (not reference types), so
they're passedbyvalue.
0 They are sealed, whichmeansthey cannot be derived fromor haveanybase class.
0 Classes inC# are different fromclassesinC++ inthe followingways:
i. There isnoaccessmodifieronthe nameof the baseclassandinheritanceisalways
public.
i i . A classcanonlybe derived fromonebaseclass.If nobaseclassis explicitly
specified,then the classwillautomaticallybe derived fromSystem.Object.
iii. In C++, the only types of class members are variables, functions, constructors,
destructors and operator overloads, C# also permits delegates, events and
properties.
iv. The access modifiers public, private and protected have the samemeaningas
in C++ but there are two additional access modifiers available: (a) Internal (b)
Protected internal
(II) INTERFACES
0 C # does not support Multiple Inheritance
0 However a classcanimplementnumberof interfaces
0 It containsmethods,properties, indexers,andevents
interface DataBind
{
voidBind(IDataBinder bind);
}
Class EditBox: Control, DataBind
{
voidDataBind.Bind(IDataBinder bind){…}
}
(III) DELEGATES
0 A delegate issimilarto a functionpointer inC / C # .
0 Using a delegate allowsa programmerto encapsulate a
reference to a methodinsidea delegate object,whichcanthen
be passed tocode.
0 Declaring adelegate:
publicdelegate voidBookDelegate(Book book);
0 Instantiating adelegate:
book.PaperbackBooks(newBookDelegate(Title));
0 Calling adelegate:
processBook(b);
(IV)SWITCHSTATEMENT:FALLTHROUGH
0 In C # a switchstatementmaynot "fallthrough"to the nextstatementif it doesanywork.
To accomplishthis,youneedto useanexplicit gotostatement:
switch(i)
{
case4:CallFuncOne();
goto case5;
case5:
C allSomeFunc();
}
If the casestatementdoesnotwork(hasnocodewithinit) thenyoucanfall :
switch(i)
{
case4: / / fall through
case5:
CallSomeFunc();
}
(V)FOREACH CONTROL
FLOW
New controlflowstatement-foreach :
C # provides an additional flow control statement, for each. For each loops
across all items in array or collection without requiring explicit specification of
the indices.
Syntax:
Foreach(double someElement inMyArray)
{
Console.WriteLine(someElement);
}
(VI)VIRTUALMETHODS
0 In C# one canchooseto override a virtual function frombase class.Derived
methodcanparticipate inpolymorphismonlyif it usesthe keywordoverride before
it.
0 In C++, if provided the samesyntax methodinderived classasbase
classvirtual method,it willbe automaticallybeoverridden.
0 In C# wehaveabstract methodsand inC++ pure virtual methods.Bothmaynot be
exactly same,but are equivalent (as pure virtual canhavefunctionbody)
0 EXAM PL E:
classBase{
publicvirtual stringVirtualMethod()
{ return "basevirtual";}
}
classDerived :Base{
publicoverride stringVirtualMethod()
{ return "Derived overriden";}
}
(VII)BOXINGAND UNBOXING
0 Boxing istheoperation of convertinga value-typeobject intoa valueof a
correspondingreferencetype.
0 Boxing inC # isimplicit.
0 Unboxing isthe operation of convertinga valueof a referencetype
(previouslyboxed) into a valueofa valuetype.
0 UnboxinginC # requiresanexplicittype cast.A boxedobject of type T
canonlybe unboxedto a T (or a nullableT).
0 E X A M P L E :
int box_var= 42; / / Value type.
object bar = box_var; / / foo is boxed to bar.
intbox_var2 = (int)bar; / / Unboxed back to value type.
(VIII)COMMON TYPESYSTEM
0 C # has a unified type system. This unified type system is called Common
Type System (CTS).
0 A unified type system implies that all types, including primitives such as
integers, are subclasses of the System.Object class. For example, every type
inheritsa ToString() method.
0 C T S separates data types into twocategories:
1. Value types
2. Referencetypes
(VIII)VALUETYPEV/S REFERENCETYPE
VA L U E TYPE:
0 Instances of value types do not have referential identity nor referential
comparison semantics i.e. equality and inequality comparisons for value types
compare the actual data values within the instances, unless the corresponding
operators areoverloaded.
0 Value types are derived from System.ValueType, always have a default
value,andcanalwaysbe created andcopied.
0 They cannot derive from each other (but can implement interfaces) and
cannot haveanexplicitdefault (parameterless)constructor.
(VIII) VALUETYPEVSREFERENCETYPE
…cont.
R E F E R E N C E TYPE:
0 Reference types have the notion of referential identity - each instance of a
reference type is inherently distinct from every other instance, even if the
data withinboth instancesisthesame.
0 It is not always possible to create an instance of a reference type, nor to
copy an existing instance, or perform a value comparison on two existing
instances.
0 Specific reference types can provide services by exposing a public
constructor or implementing a corresponding interface (such as ICloneable
orIComparable). Examples:System.String,System.Array
(IX)GENERICS
0 Generics usetype parameters, whichmakeit possible to designclassesand methodsthat do not
specify the type useduntil the classor methodisinstantiated.
0 The mainadvantage isthat one canusegenerictype parametersto create classesand methods
that canbe usedwithoutincurring the cost of runtimecastsor boxingoperations.
0 E X AM P LE :
public classGenericList<T>
{
voidAdd(T input) { }
}
classTestGenericList
{
private classExampleClass {}
static voidMain() {
/ / Declare a list of type int.
GenericList<int> list1 = newGenericList<int>();
/ / Declare a list of type string.
GenericList<string> list2 = newGenericList<string>();
}
}
(X) REFLECTION
0 Reflection isusefulinthe following situations:
0 When you need to accessattributes inyour program'smetadata. See the
topicAccessingAttributes With Reflection.
0 For examiningandinstantiating types inanassembly.
0 For buildingnewtypes at runtime.Use classes
inSystem.Reflection.Emit.
0 For performinglate binding,accessingmethodsontypes created atrun
time.
0 EXA MPLE:
/ / Using GetType to obtain type information:
int i= 42;
System.Typetype = i.GetType();
System.Console.WriteLine(type);
ADVANTAGESOFC#
0 It allowsdesigntimeand runtimeattributes to beincluded.
0 It allowsintegrated documentation usingXML.
0 No header files,IDL etc. are required.
0 It canbe embedded into webpages.
0 Garbage collection ensuresnomemoryleakage and stray pointers.
0 Due to exceptions, error handlingiswell-plannedand not doneasan
afterthought.
0 Allows provisionfor interoperability.
APPLICATIONSOFC#
0 The threemaintypesof applicationthat canbe writteninC # are:
1. Winforms- WindowslikeForms.
2. Console - CommandlineInputandOutput.
3. Web Sites :Web sitesneedIIS (Microsoft's webserver)and
A S P. N E T.
INTRODUCTIONTO.NET FRAMEWORK
0 . N E T framework is a software framework primarily for Microsoft Windows. It
includes a large library & provides language interoperability across several
programminglanguages.
0 Programs written for the . N E T Framework execute in a software environment,
as opposed to a hardware one for most other programs. Common examples of
suchprogramsincludeVisual Studio, Team Explorer UI, Sharp Develop .
0 Programmers combine their own source code with the . N E T Framework and
other libraries. The . N E T Framework is intended to be used by most new
applicationscreated forthe Windowsplatform.
HISTORYOF .NET
0 . N E T was developed by Microsoft in the mid 1990s, originally under the
nameof ‘NextGeneration WindowsServices’.
0 . N E T 1.1 was the first version to be included as a part of the Windows
O S . It provided built-in support for A S P .NET, O D B C & Oracle
databases. It provided a higher level of trust by allowing the user to enable
Code AccessSecurity inASP. N E T.
0 Currently, Windows 8 supports version 4.5of . N E T whichsupports
provisionfor ‘Metro Style Apps’
DESIGNFEATURES
0 Interoperability: . N E T Framework provides means to access functionality
implemented in newer and older programs that execute outside the . N E T
environment. Access to C O M components is provided in the
System.Runtime.InteropServices and System.EnterpriseServices
namespacesof theframework.
0 Common Language Runtime engine: C L R serves as the execution engine of
the . N E T Framework. All . N E T programs execute under the supervision
of the CLR, guaranteeing certain properties and behaviors in the areas of
memorymanagement,security,andexceptionhandling.
0 Language Independence: . N E T Framework introduces Common Type
System which define all possible data types & programming constructs
supported by C L R & ruled for their interaction as per CLI specification.
This allows the exchange of types & object instances between libraries &
their applicationswrittenusinganyconforming. N E T language.
DESIGNFEATURES…cont.
0 BCL: It is a library of functionality which is available to all languages using
the Framework. It consists of classes, interfaces or reusable types that
integrate withCLR.
0 Portability: The framework allows platform-agnostic & cross-platform
implementations for other OS’. The availability of specifications for the
CLI, & C# make it possible for third parties to create compatible
implementationsofthe framework& it’s languagesonother platforms.
.NETFRAMEWORKARCHITECTURE
.NETARCHITECTUREDESIGN
CLR:
0 The software environment in whichprograms for . N E T framework run is known as the ‘Common
Language Runtime’. It is Microsoft’s implementation of a ‘Common Language Infrastructure’. Its
purposeisto provide a language-neutral platform for applicationdevelopment & execution.
0 The CLI isresponsiblefor exceptionhandling,garbage collection,security& interoperability.
0 The CIL codeishousedinCLI assemblies.The assemblyconsistsof manyfiles,oneof whichmust
contain metadata forassembly.
VM:
0 An applicationVM providesservicessuchassecurity, memorymanagement& exception handling.
0 The security mechanismsupports 2mainfeatures.
0 Code Access Security: It isbasedonproof that isrelatedto a specificassembly.It usesthe sameto
determinepermissionsgranted to thecode.
0 Validation & Verification: Validation determineswhetherthe code satisfiesspecified requirements
andVerification determineswhetherthe conditionsimposedare satisfiedor not.
.NETARCHITECTURE
DESIGN…cont.
Class Library:
0 The classlibrary & C L R essentiallyconstitute the . N E T Framework.The
Framework’sbaseclasslibraryprovidesUI, data access,databaseconnectivity,
algorithms,networkcommunications& webapplicationdevelopment.
0 In spite of the varied functionality,the B C L includesa smallsubsetof the entire
classlibrary&isthe core set of classesthat serveasthe basicAPI of the CLR.
0 The Framework Class Library isa superset of B C L & refers to the entire class
library which includes libraries for A D O . N E T, AS P. NE T, Windows Forms,
etc.
0 It ismuchlarger inscopecompared to C++ & comparableto librariesinJava.
.NETANDOBJECT- ORIENTED
APPROACH
0 Memory management in .N E T Framework is a crucial aspect.
0 Memory is allocated to instantiations of . N E T objects from the managed
heap, a pool of memory managed by the CLR. As long as there exists a
reference to an object, either a direct reference or via a graph, the object is
consideredto be inuse.
0 When there is no reference to an object, and it cannot be reached or used,
it becomesgarbage,eligibleforcollection
0 N E T Framework includes a garbage collector which runs periodically, on
a separate thread from the application's thread, that enumerates all the
unusableobjects andreclaimsthe memoryallocated tothem.
GARBAGECOLLECTION
GARBAGECOLLECTION…cont.
0 Each . N E T application has a set of roots, which are pointers to objects on
the managed heap (managed objects). These may be references to static
objects, objects defined as local variables or method parameters currently in
scope,objectsreferred to by C P U registers
0 When the G C runs, it pauses the application, and for each object referred to
in the root, it recursively collects all the objects reachable from the root
objects andmarksthemasreachable.
0 It uses CLI metadata and reflection to discover the objects encapsulated by
an object, and then recursively walk them. It then enumerates all the objects on
the heap (which were initially allocated contiguously) using reflection. All
objects not markedasreachablearegarbage.
GARBAGECOLLECTION…cont.
The G C used by . N E T Framework is actually ’generational’. Objects are
assigned a generation; newly created objects belong to ’Generation 0’. The
objects that survive a garbage collection are tagged as ’Generation 1’, and
the Generation 1 objects that survive another collection are ‘Generation 2’
objects.The . N E T Frameworkusesupto Generation 2 objects.
GUIAPPLICATIONSUSING C# &.NET
0 Windowsformisusedto create applicationswitha userinterface.
0 The followingarethe stepsto createa WindowsFormApplication:
i. Open a newProject andchoosethe WindowsFormApplication
ii.Start dragging componentsfromthe Toolbox to the Form.The form
will look somethinglikethis:
GUIAPPLICATIONS USING
C# &.NET…cont.
iii.As componentsare added to the Form, Visual Studio assignsdefault
namesto eachone.It isviathesenamesthat anyC # codewillinteractwiththe
userinterface of theapplication.
iv.The nameof thesecomponentscanbe changedinthe Properties panel
v.In addition to changingthe namesofcomponents
it isalsopossibleto changea myriadarray of
different properties viathe propertiespanel.
GUIAPPLICATIONS USING
C# &.NET…cont.
vi.Adding behaviorto a VisualStudio C # application:
The nexttaskincreatingourapplicationisto add somefunctionalityso
that thingshappen whenwepressthe twobuttons inour form.This
behavioriscontrolledviaevents.For example,whena button ispressed
a Click eventistriggered.
GUIAPPLICATIONS USING
C# &.NET…cont.
0 Codes canbe added for onButton Click events.Some examplesare:
(I) private voidcloseButton_Click(object sender,EventArgse)
{
Close();
}
(II) private voidhelloButton_Click(object sender,EventArgse)
{
welcomeText.Text = "Hello "+nameText.Text;
}
ADVANTAGESOF.NET
0 Platformindependent
0 Supports multipleprogramminglanguages
0 Easy todeploy
0 Supports varioussecurity features suchascryptography,
application domain,verification processetc.
WRAPPINGUP
0 Introduced basicconcepts of C# programming.
0 Discussed similaritiesand differences between C# & other
programminglanguages(C,C++,Java).
0 Discussed Object-Oriented behaviour of C#.
0 Introduced concepts related . N E T framework.
0 Explained . N E T architecture.
0 Shed light uponObject-Oriented approach in. N E T framework.
0 Advantages &Applications of C# and .NET.
C# and .net framework

More Related Content

C# and .net framework

  • 2. AGENDA 0 Introduction of C # 0 History of C # 0 Design Goals 0 Why C#? :Features 0 C # & Object-OrientedApproach 0 Advantages of C # 0 Applications of C # 0 Introduction to .Net Framework 0 History of .Net 0 Design Features 0 .Net Architecture 0 .Net & Object OrientedApproach 0 Application of . N E T :G U I 0 Wrapping Up 0 References
  • 3. INTRODUCTIONTO C# 0 C # is a multi-paradigm programming language which is based on object- oriented andcomponent-orientedprogrammingdisciplines. 0 It provides a framework for free intermixing constructs from different paradigms. 0 It usesthe “besttool for the job”sincenooneparadigmsolvesallproblemsin the mostefficientway.
  • 4. BRIEFHISTORY 0 C# was developed by Microsoft with Anders Hejlsberg as the principal designer and lead architect, within its . N E T initiative and it made its appearance in2000. 0 Anders Hejlsberg and his team wanted to build a new programming language that would help to write classlibraries in a . N E T framework. He claimedthat C # wasmuchcloserto C++ initsdesign. 0 The name"C sharp"wasinspired by musicalnotation where a sharp indicates that the writtennoteshouldbe madea semitonehigherinpitch. 0 Ever since its inception, C# hascontroversially been stated as an imitation of Java. However, through the course of time, both Java and C # have exhibited distinct features whichsupport strongobject-oriented designprinciples.
  • 5. DESIGNGOALS 0 C # wasintended tobe a simple,modern,object-oriented language. 0 The language and implementation had to provide support for software engineering principles like strong type checking, array bounds checking and automaticgarbagecollection. 0 The language was intended for development of software components suitable for deploymentindistributedenvironments. 0 Source code portability was importantfor programmerswhowere familiar withC andC++. 0 Support for internalizationto adapt thesoftwareto different languages.
  • 6. WHYC# ? : FEATURES 0 C # isthe first“component-oriented” languageinthe C / C + + family. 0 The big ideaof C # isthat everythingisanobject. 0 C # is a programming language that directly reflects the underlying Common Language Infrastructure (CLI). Most of its intrinsic types correspond to value-types implemented by the CLI framework. 0 Type-safety: C # is more type safe than C++. Type safety is the extent to which a programminglanguagediscouragesor prevents typeerrors. 0 C#, likeC++, butunlikeJava, supportsoperator overloading. 0 Managed memory is automatically garbage collected. Garbage collection addresses the problem of memory leaks by freeing the programmer of responsibility for releasing memory that isnolongerneeded. 0 C # provides properties as syntactic sugar for a commonpattern in which a pair of methods, accessor (getter) and mutator (setter) encapsulate operations on a single attribute of a class.
  • 7. WHYC# ? :FEATURES…cont. 0 In addition to the try...catch construct to handle exceptions, C# has a try...finally construct to guarantee execution of the code in the finallyblock, whetheranexceptionoccursornot. 0 Unlike Java, C # does not have checked exceptions. This has been a consciousdecisionbased onthe issuesof scalabilityandversionability. 0 Multiple inheritance is not supported, although a class can implement any number of interfaces. This was a design decision to avoid complication and simplifyarchitecturalrequirementsthroughoutCLI. 0 C # supports a strict Boolean data type, bool. Statements that take conditions, such as while and if, require an expression of a type that implementsthe true operator, suchastheboolean type.
  • 8. C# &OBJECTORIENTEDAPPROACH (I) Structs &Classes (II) Interfaces (III) Delegates (IV) Switch Statement: FallThrough (V) For Each: Control Flow (VI)Virtual Methods (VII) Boxing &Unboxing (VIII) CommonType System (IX) Generics (X) Reflection
  • 9. (I) STRUCTS&CLASSES INC# 0 In C# structs are very different from classes. Structs in C# are designed to encapsulate lightweight objects. They are value types (not reference types), so they're passedbyvalue. 0 They are sealed, whichmeansthey cannot be derived fromor haveanybase class. 0 Classes inC# are different fromclassesinC++ inthe followingways: i. There isnoaccessmodifieronthe nameof the baseclassandinheritanceisalways public. i i . A classcanonlybe derived fromonebaseclass.If nobaseclassis explicitly specified,then the classwillautomaticallybe derived fromSystem.Object. iii. In C++, the only types of class members are variables, functions, constructors, destructors and operator overloads, C# also permits delegates, events and properties. iv. The access modifiers public, private and protected have the samemeaningas in C++ but there are two additional access modifiers available: (a) Internal (b) Protected internal
  • 10. (II) INTERFACES 0 C # does not support Multiple Inheritance 0 However a classcanimplementnumberof interfaces 0 It containsmethods,properties, indexers,andevents interface DataBind { voidBind(IDataBinder bind); } Class EditBox: Control, DataBind { voidDataBind.Bind(IDataBinder bind){…} }
  • 11. (III) DELEGATES 0 A delegate issimilarto a functionpointer inC / C # . 0 Using a delegate allowsa programmerto encapsulate a reference to a methodinsidea delegate object,whichcanthen be passed tocode. 0 Declaring adelegate: publicdelegate voidBookDelegate(Book book); 0 Instantiating adelegate: book.PaperbackBooks(newBookDelegate(Title)); 0 Calling adelegate: processBook(b);
  • 12. (IV)SWITCHSTATEMENT:FALLTHROUGH 0 In C # a switchstatementmaynot "fallthrough"to the nextstatementif it doesanywork. To accomplishthis,youneedto useanexplicit gotostatement: switch(i) { case4:CallFuncOne(); goto case5; case5: C allSomeFunc(); } If the casestatementdoesnotwork(hasnocodewithinit) thenyoucanfall : switch(i) { case4: / / fall through case5: CallSomeFunc(); }
  • 13. (V)FOREACH CONTROL FLOW New controlflowstatement-foreach : C # provides an additional flow control statement, for each. For each loops across all items in array or collection without requiring explicit specification of the indices. Syntax: Foreach(double someElement inMyArray) { Console.WriteLine(someElement); }
  • 14. (VI)VIRTUALMETHODS 0 In C# one canchooseto override a virtual function frombase class.Derived methodcanparticipate inpolymorphismonlyif it usesthe keywordoverride before it. 0 In C++, if provided the samesyntax methodinderived classasbase classvirtual method,it willbe automaticallybeoverridden. 0 In C# wehaveabstract methodsand inC++ pure virtual methods.Bothmaynot be exactly same,but are equivalent (as pure virtual canhavefunctionbody) 0 EXAM PL E: classBase{ publicvirtual stringVirtualMethod() { return "basevirtual";} } classDerived :Base{ publicoverride stringVirtualMethod() { return "Derived overriden";} }
  • 15. (VII)BOXINGAND UNBOXING 0 Boxing istheoperation of convertinga value-typeobject intoa valueof a correspondingreferencetype. 0 Boxing inC # isimplicit. 0 Unboxing isthe operation of convertinga valueof a referencetype (previouslyboxed) into a valueofa valuetype. 0 UnboxinginC # requiresanexplicittype cast.A boxedobject of type T canonlybe unboxedto a T (or a nullableT). 0 E X A M P L E : int box_var= 42; / / Value type. object bar = box_var; / / foo is boxed to bar. intbox_var2 = (int)bar; / / Unboxed back to value type.
  • 16. (VIII)COMMON TYPESYSTEM 0 C # has a unified type system. This unified type system is called Common Type System (CTS). 0 A unified type system implies that all types, including primitives such as integers, are subclasses of the System.Object class. For example, every type inheritsa ToString() method. 0 C T S separates data types into twocategories: 1. Value types 2. Referencetypes
  • 17. (VIII)VALUETYPEV/S REFERENCETYPE VA L U E TYPE: 0 Instances of value types do not have referential identity nor referential comparison semantics i.e. equality and inequality comparisons for value types compare the actual data values within the instances, unless the corresponding operators areoverloaded. 0 Value types are derived from System.ValueType, always have a default value,andcanalwaysbe created andcopied. 0 They cannot derive from each other (but can implement interfaces) and cannot haveanexplicitdefault (parameterless)constructor.
  • 18. (VIII) VALUETYPEVSREFERENCETYPE …cont. R E F E R E N C E TYPE: 0 Reference types have the notion of referential identity - each instance of a reference type is inherently distinct from every other instance, even if the data withinboth instancesisthesame. 0 It is not always possible to create an instance of a reference type, nor to copy an existing instance, or perform a value comparison on two existing instances. 0 Specific reference types can provide services by exposing a public constructor or implementing a corresponding interface (such as ICloneable orIComparable). Examples:System.String,System.Array
  • 19. (IX)GENERICS 0 Generics usetype parameters, whichmakeit possible to designclassesand methodsthat do not specify the type useduntil the classor methodisinstantiated. 0 The mainadvantage isthat one canusegenerictype parametersto create classesand methods that canbe usedwithoutincurring the cost of runtimecastsor boxingoperations. 0 E X AM P LE : public classGenericList<T> { voidAdd(T input) { } } classTestGenericList { private classExampleClass {} static voidMain() { / / Declare a list of type int. GenericList<int> list1 = newGenericList<int>(); / / Declare a list of type string. GenericList<string> list2 = newGenericList<string>(); } }
  • 20. (X) REFLECTION 0 Reflection isusefulinthe following situations: 0 When you need to accessattributes inyour program'smetadata. See the topicAccessingAttributes With Reflection. 0 For examiningandinstantiating types inanassembly. 0 For buildingnewtypes at runtime.Use classes inSystem.Reflection.Emit. 0 For performinglate binding,accessingmethodsontypes created atrun time. 0 EXA MPLE: / / Using GetType to obtain type information: int i= 42; System.Typetype = i.GetType(); System.Console.WriteLine(type);
  • 21. ADVANTAGESOFC# 0 It allowsdesigntimeand runtimeattributes to beincluded. 0 It allowsintegrated documentation usingXML. 0 No header files,IDL etc. are required. 0 It canbe embedded into webpages. 0 Garbage collection ensuresnomemoryleakage and stray pointers. 0 Due to exceptions, error handlingiswell-plannedand not doneasan afterthought. 0 Allows provisionfor interoperability.
  • 22. APPLICATIONSOFC# 0 The threemaintypesof applicationthat canbe writteninC # are: 1. Winforms- WindowslikeForms. 2. Console - CommandlineInputandOutput. 3. Web Sites :Web sitesneedIIS (Microsoft's webserver)and A S P. N E T.
  • 23. INTRODUCTIONTO.NET FRAMEWORK 0 . N E T framework is a software framework primarily for Microsoft Windows. It includes a large library & provides language interoperability across several programminglanguages. 0 Programs written for the . N E T Framework execute in a software environment, as opposed to a hardware one for most other programs. Common examples of suchprogramsincludeVisual Studio, Team Explorer UI, Sharp Develop . 0 Programmers combine their own source code with the . N E T Framework and other libraries. The . N E T Framework is intended to be used by most new applicationscreated forthe Windowsplatform.
  • 24. HISTORYOF .NET 0 . N E T was developed by Microsoft in the mid 1990s, originally under the nameof ‘NextGeneration WindowsServices’. 0 . N E T 1.1 was the first version to be included as a part of the Windows O S . It provided built-in support for A S P .NET, O D B C & Oracle databases. It provided a higher level of trust by allowing the user to enable Code AccessSecurity inASP. N E T. 0 Currently, Windows 8 supports version 4.5of . N E T whichsupports provisionfor ‘Metro Style Apps’
  • 25. DESIGNFEATURES 0 Interoperability: . N E T Framework provides means to access functionality implemented in newer and older programs that execute outside the . N E T environment. Access to C O M components is provided in the System.Runtime.InteropServices and System.EnterpriseServices namespacesof theframework. 0 Common Language Runtime engine: C L R serves as the execution engine of the . N E T Framework. All . N E T programs execute under the supervision of the CLR, guaranteeing certain properties and behaviors in the areas of memorymanagement,security,andexceptionhandling. 0 Language Independence: . N E T Framework introduces Common Type System which define all possible data types & programming constructs supported by C L R & ruled for their interaction as per CLI specification. This allows the exchange of types & object instances between libraries & their applicationswrittenusinganyconforming. N E T language.
  • 26. DESIGNFEATURES…cont. 0 BCL: It is a library of functionality which is available to all languages using the Framework. It consists of classes, interfaces or reusable types that integrate withCLR. 0 Portability: The framework allows platform-agnostic & cross-platform implementations for other OS’. The availability of specifications for the CLI, & C# make it possible for third parties to create compatible implementationsofthe framework& it’s languagesonother platforms.
  • 28. .NETARCHITECTUREDESIGN CLR: 0 The software environment in whichprograms for . N E T framework run is known as the ‘Common Language Runtime’. It is Microsoft’s implementation of a ‘Common Language Infrastructure’. Its purposeisto provide a language-neutral platform for applicationdevelopment & execution. 0 The CLI isresponsiblefor exceptionhandling,garbage collection,security& interoperability. 0 The CIL codeishousedinCLI assemblies.The assemblyconsistsof manyfiles,oneof whichmust contain metadata forassembly. VM: 0 An applicationVM providesservicessuchassecurity, memorymanagement& exception handling. 0 The security mechanismsupports 2mainfeatures. 0 Code Access Security: It isbasedonproof that isrelatedto a specificassembly.It usesthe sameto determinepermissionsgranted to thecode. 0 Validation & Verification: Validation determineswhetherthe code satisfiesspecified requirements andVerification determineswhetherthe conditionsimposedare satisfiedor not.
  • 29. .NETARCHITECTURE DESIGN…cont. Class Library: 0 The classlibrary & C L R essentiallyconstitute the . N E T Framework.The Framework’sbaseclasslibraryprovidesUI, data access,databaseconnectivity, algorithms,networkcommunications& webapplicationdevelopment. 0 In spite of the varied functionality,the B C L includesa smallsubsetof the entire classlibrary&isthe core set of classesthat serveasthe basicAPI of the CLR. 0 The Framework Class Library isa superset of B C L & refers to the entire class library which includes libraries for A D O . N E T, AS P. NE T, Windows Forms, etc. 0 It ismuchlarger inscopecompared to C++ & comparableto librariesinJava.
  • 30. .NETANDOBJECT- ORIENTED APPROACH 0 Memory management in .N E T Framework is a crucial aspect. 0 Memory is allocated to instantiations of . N E T objects from the managed heap, a pool of memory managed by the CLR. As long as there exists a reference to an object, either a direct reference or via a graph, the object is consideredto be inuse. 0 When there is no reference to an object, and it cannot be reached or used, it becomesgarbage,eligibleforcollection 0 N E T Framework includes a garbage collector which runs periodically, on a separate thread from the application's thread, that enumerates all the unusableobjects andreclaimsthe memoryallocated tothem.
  • 32. GARBAGECOLLECTION…cont. 0 Each . N E T application has a set of roots, which are pointers to objects on the managed heap (managed objects). These may be references to static objects, objects defined as local variables or method parameters currently in scope,objectsreferred to by C P U registers 0 When the G C runs, it pauses the application, and for each object referred to in the root, it recursively collects all the objects reachable from the root objects andmarksthemasreachable. 0 It uses CLI metadata and reflection to discover the objects encapsulated by an object, and then recursively walk them. It then enumerates all the objects on the heap (which were initially allocated contiguously) using reflection. All objects not markedasreachablearegarbage.
  • 33. GARBAGECOLLECTION…cont. The G C used by . N E T Framework is actually ’generational’. Objects are assigned a generation; newly created objects belong to ’Generation 0’. The objects that survive a garbage collection are tagged as ’Generation 1’, and the Generation 1 objects that survive another collection are ‘Generation 2’ objects.The . N E T Frameworkusesupto Generation 2 objects.
  • 34. GUIAPPLICATIONSUSING C# &.NET 0 Windowsformisusedto create applicationswitha userinterface. 0 The followingarethe stepsto createa WindowsFormApplication: i. Open a newProject andchoosethe WindowsFormApplication ii.Start dragging componentsfromthe Toolbox to the Form.The form will look somethinglikethis:
  • 35. GUIAPPLICATIONS USING C# &.NET…cont. iii.As componentsare added to the Form, Visual Studio assignsdefault namesto eachone.It isviathesenamesthat anyC # codewillinteractwiththe userinterface of theapplication. iv.The nameof thesecomponentscanbe changedinthe Properties panel v.In addition to changingthe namesofcomponents it isalsopossibleto changea myriadarray of different properties viathe propertiespanel.
  • 36. GUIAPPLICATIONS USING C# &.NET…cont. vi.Adding behaviorto a VisualStudio C # application: The nexttaskincreatingourapplicationisto add somefunctionalityso that thingshappen whenwepressthe twobuttons inour form.This behavioriscontrolledviaevents.For example,whena button ispressed a Click eventistriggered.
  • 37. GUIAPPLICATIONS USING C# &.NET…cont. 0 Codes canbe added for onButton Click events.Some examplesare: (I) private voidcloseButton_Click(object sender,EventArgse) { Close(); } (II) private voidhelloButton_Click(object sender,EventArgse) { welcomeText.Text = "Hello "+nameText.Text; }
  • 38. ADVANTAGESOF.NET 0 Platformindependent 0 Supports multipleprogramminglanguages 0 Easy todeploy 0 Supports varioussecurity features suchascryptography, application domain,verification processetc.
  • 39. WRAPPINGUP 0 Introduced basicconcepts of C# programming. 0 Discussed similaritiesand differences between C# & other programminglanguages(C,C++,Java). 0 Discussed Object-Oriented behaviour of C#. 0 Introduced concepts related . N E T framework. 0 Explained . N E T architecture. 0 Shed light uponObject-Oriented approach in. N E T framework. 0 Advantages &Applications of C# and .NET.