Download - MCA_512_2011_12_LS_UNIT _1
DOT NET FRAMEWORK
MCA 512
Syllabus
Unit-1: The .Net framework: Introduction, The Origin of .Net Technology, Common Language Runtime (CLR), Common Type System (CTS), Common Language Specification (CLS), Microsoft Intermediate Language (MSIL), Just-In –Time Compilation, Framework Base Classes.
Unit-II: C -Sharp Language (C#): Introduction, Data Types, Identifiers, Variables, Constants, Literals,Array and Strings, Object and Classes, Inheritance and Polymorphism, Operator Overloading, Interfaces, Delegates and Events. Type conversion.
Unit-III : C# Using Libraries: Namespace- System, Input-Output, Multi-Threading, Networking and sockets, Managing Console I/O Operations, Windows Forms, Error Handling.
Unit-IV: Advanced Features Using C#: Web Services, Window Services, Asp.net Web Form Controls, ADO.Net. Distributed Application in C#, Unsafe Mode, Graphical Device interface with C#.
Unit-V : .Net Assemblies and Attribute: .Net Assemblies features and structure, private and share assemblies, Built-In attribute and custom attribute. Introduction about generic..
References
1. Wiley,” Beginning Visual C# 2008”,Wrox
2. Fergal Grimes,” Microsoft .Net for Programmers”. (SPI)
3. Balagurusamy,” Programming with C#”, (TMH)
4. Mark Michaelis, “Essential C# 3.0: For .NET Framework 3.5, 2/e, Pearson Education
5. Shibi Parikkar, “ C# with .Net Frame Work” , Firewall Media.
.NET Platform RoadmapSecond Generation Web Apps
Combination of “stateless” Web protocols with DNS and IP routing have enabled mass-scale “Geo-Scalability”
““StatefulStateful””
““Stateless” andStateless” and““Geo-Scalable”Geo-Scalable”
RichRichClient LogicClient Logic
RichRichClient LogicClient Logic
ServersServersData, HostsData, Hosts
ServersServersData, HostsData, Hosts
OS OS ServicesServices
BizBizTier LogicTier Logic
BizBizTier LogicTier Logic
BrowsersBrowsersBrowsersBrowsers
Separation of data and business logic provide greater scalability and performance while accessing enterprise and legacy data
COM+ Services improve reliability, scalability and manageability. IE provides D/HTML for better interactivity
.NET Platform Roadmap Web Services: The Next Generation
StandardStandardBrowsersBrowsers
StandardStandardBrowsersBrowsers
SmarterSmarterClientsClients
SmarterSmarterClientsClients
SmarterSmarterDevicesDevices
SmarterSmarterDevicesDevices Open Internet Open Internet
Communications Protocols Communications Protocols (HTTP, SMTP, XML, SOAP) (HTTP, SMTP, XML, SOAP) Richer, MoreRicher, More
Productive UserProductive UserExperienceExperience
Applications LeverageApplications LeverageGlobally-AvailableGlobally-Available
Federated Web ServicesFederated Web Services
Applications Become Applications Become Programmable Web ServicesProgrammable Web Services
OS OS ServicesServices
BizBizTier LogicTier Logic
BizBizTier LogicTier Logic
Biz Logic Biz Logic & & Web ServiceWeb Service
OSOSServicesServices
OSOSServicesServices
Public WebPublic WebServicesServices
Building BlockBuilding BlockServicesServices
InternalInternalServicesServices
XMLXML
XMLXML
XMLXML
ServersServersData, HostsData, Hosts
ServersServersData, HostsData, Hosts
XMLXML
OtherOther ServicesServices
XMLXML
XMLXML
XMLXML
HTMLHTML
Internet ProtocolsInternet Protocols
SOAP, HTTP, SMTP, XMLSOAP, HTTP, SMTP, XML
.NET Platform RoadmapThe .NET Platform
ApplicationsApplications Using Your Using Your
ServiceService
ApplicationsApplications Using Your Using Your
ServiceService
.NET Enterprise Servers.NET Enterprise Servers.NET Enterprise Servers.NET Enterprise Servers
.NET Foundation.NET FoundationServicesServices
.NET Foundation.NET FoundationServicesServices
Your Internal Your Internal ServicesServices
Your Internal Your Internal ServicesServices
Visual Visual Studio.NETStudio.NET
Visual Visual Studio.NETStudio.NET
Your Application Your Application and Web Serviceand Web Service
Your Application Your Application and Web Serviceand Web Service
End-UserEnd-UserClientsClients
Third Party Third Party Web ServicesWeb Services
Third Party Third Party Web ServicesWeb Services
.NET .NET FrameworkFramework
OrchestrationOrchestrationOrchestrationOrchestration
Windows Windows ME, 2000, XP, .NETME, 2000, XP, .NET
Windows Windows ME, 2000, XP, .NETME, 2000, XP, .NET
Op
erat
ion
sO
per
atio
ns
Op
erat
ion
sO
per
atio
ns
The .NET Evolution
Before COM, applications were completely separate entities with little or no integration
Application
Code and data structures
The .NET Evolution
COM provides a way for components to integrate. However, each component must provide the “plumbing” and objects cannot directly interact.
The .NET Evolution
With the .NET Framework common language runtime, components are built on a common substrate. No “plumbing” is needed and objects can directly interact
What Is the Microsoft .NET Platform?
.Net Framework Design Goals
Simplify developmentMore power, less plumbing
Unify programming modelsAcross all languages and application types
Utilize web standards and best practicesRich XML, standard protocols, stateless
Easier to deploy, run, & maintainFor components, versioning, availability
Benefits of .NET Framework
The Microsoft .NET solution comprises four core components:
• .NET Building Block Services, or programmatic access to certain services, such as file storage, calendar, and Passport.NET (an identity verification service).
• .NET device software, which will run on new Internet devices. • The .NET user experience, which includes such features as the
natural interface, information agents, and smart tags, a technology that automates hyperlinks to information related to words and phrases in user-created documents.
• The .NET infrastructure, which comprises the .NET Framework, Microsoft Visual Studio.NET, the .NET Enterprise Servers, and Microsoft Windows.NET.
.NET Framework Architecture
• The .NET infrastructure is the part of .NET that most developers are referring to when they refer to .NET. The .NET infrastructure refers to all the technologies that make up the new environment for creating and running robust, scalable, distributed applications. The part of .NET that lets us develop these applications is the .NET Framework. – The .NET Framework consists of the – Common Language Runtime (CLR)– .NET Framework class libraries( Base Class Library (BCL)).
(Note: If you're familiar with either the Microsoft Foundation Classes (MFC) or Borland's Object Windows Library (OWL), you're already familiar with class libraries. The .NET Framework class libraries include support for everything from file I/O and database I/O to XML and SOAP. In fact, the .NET Framework class libraries are so vast that it would easily take a book just to give a superficial overview of all the supported classes. )
.NET Framework Architecture
Base Class LibraryBase Class Library
Common Language SpecificationCommon Language Specification
Common Language RuntimeCommon Language Runtime
ADO.NET: Data and XMLADO.NET: Data and XML
VBVB C++C++ C#C#V
isual S
tud
io.N
ET
Visu
al Stu
dio
.NE
TJScriptJScript ……
WindowsWindowsFormsForms
Base Class LibraryBase Class Library
Common Language SpecificationCommon Language Specification
Common Language RuntimeCommon Language Runtime
ADO.NET: Data and XMLADO.NET: Data and XML
VBVB C++C++ C#C#
ASP.NET: Web ServicesASP.NET: Web Servicesand Web Formsand Web Forms
JScriptJScript ……
WindowsWindowsFormsForms
Visu
al Stu
dio
.NE
TV
isual S
tud
io.N
ET
Base Class LibraryBase Class Library
Common Language SpecificationCommon Language Specification
Common Language RuntimeCommon Language Runtime
ADO.NET: Data and XMLADO.NET: Data and XML
VBVB C++C++ C#C#
ASP.NET: Web ServicesASP.NET: Web Servicesand Web Formsand Web Forms
JScriptJScript ……
WindowsWindowsFormsForms
Common Language Runtime - Overview
• Platform for .NET applications• Provides runtime support• Provides security features• Enables interoperation of applications
Other Application Other Application (CLR)(CLR)
Other Application Other Application (CLR)(CLR)
Your ApplicationYour Application(CLR)(CLR)
Your ApplicationYour Application(CLR)(CLR)
Other Application Other Application (Other platform)(Other platform)
Other Application Other Application (Other platform)(Other platform)
XML, SOAP, etc.XML, SOAP, etc.XML, SOAP, etc.XML, SOAP, etc.
CLRCLRCLRCLR
Components of CLR
• Class Loader: This loads classes into the runtime.• MSIL to native code compiler: This converts MSIL code into native
code.• Code manager: This manager the code during execution i.e provides
code check, the resources it needs during execution.• Garbage Collector: provide automatic memory management and
avoid memory leaks.• Security Engine: This enforces security restrictions and CAS.• Type Checker: This enforces strict type checking.
Components of CLR(continued..)
• Thread Support: This provides multithreading support to applications.
• Exception Manager : This provides a mechanism to handle the run-time exceptions.
• Debug Engine : Allow you to debug different type of applications.
• COM marshaler : This allows .net application to exchange data with COM applications.
• BASE Class library : This provides the types the applications needed at runtime.
The Common Language Specification
• The Common Language Specification (CLS) defines the common standards to which languages and developers must adhere if they want their components and applications to be widely useable by other .NET-compatible languages.
• The CLS allows Visual Basic .NET developers to create applications as part of a multiple-language team with the knowledge that there will be no problems integrating the different languages.
• The CLS even allows Visual Basic .NET developers to inherit from classes defined in different languages.
Microsoft Intermediate Language and the JITters
• To make it easy for language writers to port their languages to .NET, Microsoft developed a language akin to assembly language called Microsoft intermediate language (MSIL). To compile applications for .NET, compilers take source code as input and produce MSIL as output.
• MSIL itself is a complete language that you can write applications in. However, as with assembly language, you would probably never do so except in unusual circumstances. Because MSIL is its own language, each compiler team makes its own decision about how much of the MSIL it will support. However, if you're a compiler writer and you want to create a language that does interoperate with other languages, you should restrict yourself to features specified by the CLS.
• You write source code in C# and compile it using the C# compiler (csc.exe) into an EXE. • The C# compiler outputs the MSIL code and a manifest into a read-only part of the EXE
that has a standard PE (Win32-portable executable) header. When the compiler creates the output, it also imports a function named _ CorExeMain from the .NET runtime.
• When the application is executed, the operating system loads the PE, as well as any dependent dynamic-link libraries (DLLs), such as the one that exports the _ CorExeMain function (mscoree.dll), just as it does with any valid PE.
• The operating system loader then jumps to the entry point inside the PE, which is put there by the C# compiler. However, since the operating system obviously can't execute the MSIL code, the entry point is just a small stub that jumps to the _ CorExeMain function in mscoree.dll.
• The _ CorExeMain function starts the execution of the MSIL code that was placed in the PE.
• Since MSIL code cannot be executed directly—because it's not in a machine-executable format—the CLR compiles the MSIL by using a just-in-time (JIT) compiler (or JITter) into native CPU instructions as it processes the MSIL. JIT compiling occurs only as methods in the program are called. The compiled executable code is cached on the machine and is recompiled only if there's some change to the source code.
Three different JITters can be used to convert the MSIL into native code, depending on the
circumstances:
1. Install-time code generation Install-time code generation will compile an entire assembly into CPU-specific binary code, just as a C++ compiler does.
• An assembly is the code package that's sent to the compiler. This compilation is done at install time, when the end user is least likely to notice that the assembly is being JIT-compiled.
• The advantage of install-time code generation is that it allows you to compile the entire assembly just once before you run it. Because the entire assembly is compiled, you don't have to worry about intermittent performance issues every time a method in your code is executed the first time. When and if you use this utility depends on the size of your specific system and your deployment environment.
• Typically, if you're going to create an installation application for your system, you should go ahead and use this JITter so that the user has a fully optimized version of the system "out of the box."
2. JIT The default JITter is called at run time—in the manner it is described in the preceding numbered list—each time a method is invoked for the first time. This is akin to a "pay-as-you-go" plan and is the default if you don't explicitly run the PreJIT compiler.
3. EconoJIT Another run-time JITter, the EconoJIT is specifically designed for systems that have limited resources—for example, handheld devices with small amounts of memory. The major difference between this JITter and the regular JITter is the incorporation of something called code pitching. Code pitching allows the EconoJIT to discard the generated, or compiled, code if the system begins to run out of memory. The benefit is that the memory is reclaimed. However, the disadvantage is that if the code being pitched is invoked again, it must be compiled again as though it had never been called.
Unified Type System
• One of the key features of any development environment is its type system. After all, a development environment with a limited amount of types or a system that limits the programmer's ability to extend the system-supplied types isn't an environment with a long life expectancy.
• The .NET runtime does more than just give the developer a single, unified type system that is used across all CLS-compliant languages.
• It also lets language writers extend the type system by adding new types that look and act just like the system built-in types. This means that you, as a developer, can use all types in a uniform manner, regardless of whether they are .NET predefined types or user-created types.
Metadata and Reflection • In addition to mapping source code to MSIL instruction sequences, CLS-
compliant compilers have another equally important task: embedding metadata into the resulting EXE.
• Metadata is data that describes data. • In this context, metadata is the collection of programmatic items that constitute
the EXE, such as the types declared and the methods implemented.This metadata is similar to the type libraries (typelibs) generated with Component Object Model (COM) components.
• Not only is the metadata output from a .NET compiler substantially more expressive and complete than the COM typelibs we're accustomed to, but the metadata is also always embedded in the EXE. This way, there's no chance of losing the application's metadata or having a mismatched pair of files.
• The reason for using metadata.– It allows the .NET runtime to know at run time what types will be allocated and
what methods will be called. This enables the runtime to properly set up its environment to more efficiently run the application.
– The means by which this metadata is queried is called reflection.– The .NET Framework class libraries provide an entire set of reflection methods
that enable any application—not just the CLR—to query another application's metadata.
– Tools such as Visual Studio.NET use these reflection methods to implement features such as IntelliSense. With IntelliSense, as you type in a method name, that method's arguments pop up in a list box on the screen. Visual Studio.NET takes that functionality even further, showing all the members of a type.
– Another incredibly useful .NET tool that takes advantage of reflection is the Microsoft .NET Framework IL Disassembler (ILDASM). This powerful utility parses the target application's metadata and then displays information about the application in a treelike hierarchy.
Security
• The most important facet of any distributed application development environment is how it handles security. Thankfully for those of us who have long complained that Microsoft would never be taken seriously in the server-side enterprise solutions space without a completely new approach to security, .NET brings many concepts to the table. In fact, security begins as soon as a class is loaded by the CLR because the class loader is a part of the .NET security scheme. For example, when a class is loaded in the .NET runtime, security-related factors such as accessibility rules and self-consistency requirements are verified. In addition, security checks ensure that a piece of code has the proper credentials to access certain resources. Security code ensures role determination and identity information. These security checks even span process and machine boundaries to ensure that sensitive data is not compromised in distributed computing environments.
Deployment
• Deployment case dealing with the different binary files, Registry issues, COM components, and support library installation of products such as open database connectivity (ODBC) and Data Access Objects (DAO) is difficult.
• The key to .NET application deployment is the concept of assemblies. Assemblies are simply packages of semantically related behaviour that are built as either single-file or multiple-file entities. The specifics of how you deploy your application will vary based on whether you're developing a Web server application or a traditional desktop application for Windows. However, with the introduction of the assembly as a fully encapsulated set of functionality, deployment can be as simple as copying the necessary assemblies to a target location.
Deployment( Continue)
• Many of the problems that caused so much trouble for programmers prior to the .NET Framework have now been eliminated.
• For example, there's no need to register components,as you do with COM components and Microsoft ActiveX controls—because with metadata and reflection, all components are self-describing. The .NET run time also keeps track of the files, and the versions of the files, associated with an application. Therefore, any application that is installed is automatically associated with the files that are part of its assembly. If a setup application attempts to overwrite a file needed by another application, the .NET runtime is smart enough to allow the setup application to install the needed file, but the CLR doesn't delete the previous version of the file because it's still required by the first application.
Interoperability with Unmanaged Code
Unmanaged code is code that isn't controlled by the .NET runtime. However, unmanaged code doesn't have the advantages that managed code has, such as garbage collection, a unified type system, and metadata. Here are some situations •Managed code calling unmanaged DLL functions Let's say your application needs to interface to a C-like DLL and the company that wrote the DLL isn't adopting .NET as quickly as your company is. In this case, you still need to call into that DLL from a .NET application. •Managed code using COM components You might also need to continue supporting COM components. You do this by creating a .NET wrapper for the COM component so that the managed client thinks it's working with a .NET class. •Unmanaged code using .NET services You want to access .NET from unmanaged code. It's solved using a reciprocal approach: a COM client is fooled into thinking it's using a COM server, which is actually a .NET service of some sort.
Services of the CLR
• Memory Management• Threads• Garbage collection• Exception handling• Security• Application Isolation• Data Interaction• Encryption Services• Deployment
• The source code gets compiled to IL and the same time metadata information is created using the meta data engine. These are optionally linked with other code compiled by different compilers and the result is an EXE or DLL containing the IL code, which is saved to disk.
• The compilers work is now done. Then on execution, the IL code and any functionality from the .NET base class library is brought together using class loader.
• The combined code is optionally tested for type safety using the verifier before the JIT (Just in time) compiler comes into play.
• The JIT compiler processes the IL creating managed native code which is passed on the .NET runtime manager.
Garbage Collection
Process of automatically freeing up memory when an object it been allocated to is no longer being used
Prevents the following errors: Forgetting to destroy objects Attempting to destroy the same object more than once Destroying an active object
Anatomy of .NET applications
AssemblyAssembly
ManifestManifest
ModuleModule
MetadataMetadata
ILIL
Type•Methods•Properties•Fields
Type•Methods•Properties•Fields
Assemblies
myAssembly.DLLmyAssembly.DLL
Single ModuleSingle Module Multiple ModulesMultiple Modules
Assembly MetadataAssembly MetadataAssembly MetadataAssembly Metadata
Type MetadataType MetadataType MetadataType Metadata
IL CodeIL CodeIL CodeIL Code
Util.DLLUtil.DLL
Type MetadataType MetadataType MetadataType Metadata
IL CodeIL CodeIL CodeIL Code
Graphic.BMPGraphic.BMP
ResourcesResourcesResourcesResources
ParcelTracker.DLLParcelTracker.DLL
MetadataMetadataMetadataMetadata
IL/nativeIL/nativecodecode
IL/nativeIL/nativecodecode
ResourcesResourcesResourcesResources
MetadataMetadata(and code)(and code)
DebuggerDebugger
Schema Schema GeneratorGenerator
ProfilerProfiler
OtherOtherCompilerCompiler
Proxy GeneratorProxy Generator
Type BrowserType Browser
CompilerCompiler
SourceSourceCodeCode
XML encodingXML encoding(SDL or SUDS)(SDL or SUDS)
SerializationSerialization(e.g. SOAP)(e.g. SOAP)
DesignersDesigners
ReflectionReflection
Metadata: Creation And Use
Intermediate Language (IL)
• Assembly Language of CLR• Code is never interpreted
VBVB
VCVC
......
ScriptScript
ILIL
““Econo”-JITEcono”-JITCompilerCompiler
Standard JITStandard JITCompilerCompiler
NativeNativeCodeCode
Managed vs. Unmanaged
• Managed Code makes use of CLR services• Unmanaged Code does not use any services• Garbage Collector can be turned off• CLR offers mechanisms for managed code to interact with unmanaged code• Interoperation with hardware specific code and other platforms• Ability to reuse old code
ClassClassLoaderLoader
IL to nativeIL to nativecode compilercode compiler
CPUCPUSecuritySecuritySystemSystem
CodeCodeManagersManagers
ManagedManagedNativeNativeCodeCode
First call to methodFirst call to method
First reference to First reference to typetype
ExecutionExecutionSupportSupport
Runtime Control Flow
Built-in Support For
• Classes• Global Procedures, Static, Instance and Virtual Methods• Subroutines and Co-routines• Constructors• Inheritance (Type and Code)• Overriding and Overloading• Access Control and Hiding• Attributes
All Object Oriented
• All data types are objects, including Integers, Chars, etc.
• Single Object class for all languages
Value Types
• Represent “primitive” types in an efficient way
• Extensible
• Boxing and unboxing
Verification
• IL is verified by a verifier and guaranteed to be type safe
• Checks for type casts, memory initialization, array bounds
• Checks stack operations
Security System
• Permissions– Grant– Demand (minimal, optional, refuse)– Stack walk
• Policy – Set of permissions• Evidence – Input to policy• Zones• Cryptography• Signed XML – IETF/W3C XMLDSIG• Fully extensible
Versioning
• Multiple versions of component can be installed on machine
• A single process can use different version of component at same time
• Zero-impact installation and uninstallation (copy)
Fundamentals of Object-Oriented Programming
• Everything Is an Object – Non-object-oriented approach – Object-oriented approach
• Objects vs. Classes – There are many ways to define a class and distinguish it from an object. You can think of
a class as simply a type (just like char, int, or long) that has methods associated with it. An object is an instance of a type or class.
– A class is a blueprint for an object. You, as the developer, create this blueprint as an engineer would create the blueprint of a house. Once the blueprint is complete, you have only one blueprint for any given type of house.
– However, any number of people can purchase the blueprint and have the same house built.
– By the same token, a class is a blueprint for a given set of functionality, and an object created based on a particular class has all the functionality of the class built right in.
• Instantiation – A term unique to object-oriented programming, instantiation is simply the act of creating
an instance of a class. That instance is an object. In the following example, all we're doing is creating a class, or specification, for an object. In other words, no memory has been allocated at this time because we have only the blueprint for an object, not an actual object itself.
The Three Tenets of OOPsLanguages encapsulation, inheritance, and polymorphism 1. Encapsulation
– Encapsulation, sometimes called information hiding, is the ability to hide the internals of an object from its users and to provide an interface to only those members that you want the client to be able to directly manipulate.
– Encapsulation provides the boundary between a class's external interface—that is, the public members visible to the class's users—and its internal implementation details.
– The advantage of encapsulation for the class developer is that he can expose the members of a class that will remain static, or unchanged, while hiding the more dynamic and volatile class internals.
– Encapsulation is achieved in C# by virtue of assigning an access modifier—public, private, or protected—to each class member.
• Designing Abstractions – An abstraction refers to how a given problem is represented in the program
space. Programming languages themselves provide abstractions – as a class developer you need to think in terms of how you can best design
abstractions for your class's clients to allow the client to focus on the task at hand and not be mired in the details of how your class works.
– Advantageous in developing reusable software
• Inheritance – Inheritance relates to the programmer's ability to specify that one class has
a kind-of relationship with another class. – Through inheritance, you can create (or derive) a new class that's based on
an existing class. – You can then modify the class the way that you want and create new
objects of the derived type. This ability is the essence of creating a class hierarchy.
– Outside of abstraction, inheritance is the most significant part of a system's overall design. A derived class is the new class being created, and the base class is the one from which the new class is derived. The newly derived class inherits all the members of the base class, thereby enabling you to reuse previous work.
– Substitutability.Substitutability means that the advertised behavior of the derived class is substitutable for the base class.
– Another rule of thumb to keep in mind when creating your class hierarchies is that a derived class should require no more and promise no less than its base class on any inherited interfaces. Not adhering to this rule breaks existing code. A class's interface is a binding contract between itself and programmers using the class.
• Polymorphism – The definition for polymorphism is that it is functionality that allows old code
to call new code. – This is arguably the biggest benefit of object-oriented programming because
it allows you to extend or enhance your system without modifying or breaking existing code.
• Two benefits. – First, it gives you the ability to group objects that have a common base class
and treat them consistently – I have three different object types— SalariedEmployee,
ContractorEmployee,and HourlyEmployee—I can treat them all as Employee objects because they all derive from the Employee base class. This is how I can stuff them in an array that is defined as an array of Employee objects. Because of polymorphism, when I call one of those object's methods, the runtime will ensure that the correct derived object's method is called.
– The second advantage is that old code can use new code
C#
• Built on top of CLR
• Was designed from ground up to make use of CLR services
• Component Oriented– Properties are first class
– Events are first class
Hello World
using System;
class Hello { static void Main() { Console.WriteLine(“Hello word”); }}
.NET Framework Namespaces
Base Class Library
ADO.NET XML
ASP.NET Windows
System
System.Data System.Xml
System.Web
Globalization
Diagnostics
Configuration
Collections
Resources
Reflection
Net
IO
Threading
Text
ServiceProcess
Security
Design
ADO
SQLTypes
SQL
XPath
XSLT
Runtime
InteropServices
Remoting
Serialization
Serialization
Configuration SessionState
Caching Security
Services
Description
Discovery
Protocols
UI
HtmlControls
WebControls
System.Drawing
Imaging
Drawing2D
Text
Printing
System.Windows.Forms
Design ComponentModel
3. Data Types
Objectives
“.NET is designed around the CTS, or Common Type System. The CTS is what allows assemblies, written in different languages, to work together. To ensure interoperability across languages, Microsoft has also defined the CLS, or Common Language Specification, a subset of the CTS that all languages support. Otherwise, the types in C# are what you would expect from a modern OOPL…”
• The Common Type System• Value vs. reference types• Arrays• Namespaces
The Common Type System (CTS)
• CTS is based on a hierarchy of classes defined in FCL– all types inherit from Object (all except interface types)
St r i ng Ar r ay Val ueType Except i on Del egat e Cl ass1
Mul t i castDel egat e
Cl ass2
Cl ass3
Obj ect
Enum1
St r uct ur e1EnumPr i mi t i ve t ypes
Bool ean
Byt e
I nt 16
I nt 32
I nt 64
Char
Si ngl e
Doubl e
Deci mal
Dat eTi me
System-defined types
User-defined types
Del egat e1
Ti meSpan
Gui d
The Common Language Specification (CLS)
• Not all languages support all CTS types and features– C# supports unsigned integer types, VB.NET does not– C# is case sensitive, VB.NET is not– C# supports pointer types (in unsafe mode), VB.NET does
not– C# supports operator overloading, VB.NET does not
• CLS was drafted to promote language interoperability– vast majority of classes within FCL are CLS-compliant
Mapping C# to CTS• Language keywords map to common CTS classes:
Keyword Description Special format for literals
bool Boolean true false
char 16 bit Unicode character 'A' '\x0041' '\u0041'
sbyte 8 bit signed integer none
byte 8 bit unsigned integer none
short 16 bit signed integer none
ushort 16 bit unsigned integer none
int 32 bit signed integer none
uint 32 bit unsigned integer U suffix
long 64 bit signed integer L or l suffix
ulong 64 bit unsigned integer U/u and L/l suffix
float 32 bit floating point F or f suffix
double 64 bit floating point no suffix
decimal 128 bit high precision M or m suffix
string character sequence "hello", @"C:\dir\file.txt"
Example
• An example of using types in C#– declare before you use (compiler enforced)– initialize before you use (compiler enforced)public class App
{ public static void Main() { int width, height; width = 2; height = 4;
int area = width * height;
int x; int y = x * 2; ... }}
declarations
decl + initializer
error, x not set
Type conversion
• Some automatic type conversions available– from smaller to larger types
• Otherwise you need a cast or an explicit conversion…– typecast syntax is type name inside parentheses– conversion based on System.Convert class
int i = 5;double d = 3.2;string s = "496";
d = i;
i = (int) d;
i = System.Convert.ToInt32(s);
implicit conversion
typecast required
conversion required
Value vs. reference types
• C# separates data types into two categories• Value types:
– variable represents a value ("bits")
• Reference types:– variable represents a reference to a heap-based object– actual data resides in the object
int i;i = 10;
10
string s;s = "calico";
"calico"
How do you know which types are which?
• Memorization!• Though it's pretty obvious based on past experience
– primitive types like bool, int and double are values– remainder are reference types
int i;string s;Customer c1, c2;
i = 23;s = "a message";c1 = null;c2 = new Customer(…);
Boxing and Unboxing
• When necessary, C# will auto-convert value <==> object– value ==> object is called "boxing"– object ==> value is called "unboxing"
int i, j;object obj;string s;
i = 32;obj = i; // boxed copy!i = 19;j = (int) obj; // unboxed!
s = j.ToString(); // boxed!s = 99.ToString(); // boxed!
User-defined reference types
• Classes!– for example, Customer class we worked with earlier…
public class Customer{ public string Name; // fields public int ID;
public Customer(string name, int id) // constructor { this.Name = name; this.ID = id; }
public override string ToString() // method { return "Customer: " + this.Name; }}
Working with reference types…
• Creating, assigning, and comparing:Customer c1, c2, c3;string s1, s2;
c1 = new Customer("joe hummel", 36259);c2 = new Customer("marybeth lore", 55298);c3 = null; // c3 references no object
c3 = c1; // c3 now references same obj as c1
if (c1 == null) ... // do I ref an object? if (c1 == c2) ... // compares references if (c1.Equals(c2)) ... // compares objects
if (s1 == s2) ... // exception: == overloaded to // compare string data
Defining equality
• Classes should override Equals
public class Customer{ . . .
public override bool Equals(object obj) { Customer other; if ((obj == null) || (!(obj is Customer))) return false; // definitely not equal
other = (Customer) obj; // typecast to access return this.ID == other.ID; // equal if same id... }
GetHashCode
• If you override Equals, must also override GetHashCode:
public class Customer{ . . .
public override int GetHashCode() { return this.id.GetHashCode(); }
Arrays
• Arrays are reference types– based on Array class in FCL– must be created using new– 0-based indexing– assigned default values (0 for numeric, null for references,
etc.)int[] a;a = new int[5];
a[0] = 17;a[1] = 32;int x = a[0] + a[1] + a[4];
int l = a.Length;
element access
create
number of elements
Multi-dimensional arrays• C# supports arrays as a single object OR array of arrays
– latter allows you to implement jagged arrays
Customer[,] twoD;int[][] jagged2D;
// 2D array as single objecttwoD = new Customer[10, 100];twoD[0, 0] = new Customer(…);twoD[9, 99] = new Customer(…);
// 2D array as array of arraysjagged2D = new int[10][];jagged2D[0] = new int[10];jagged2D[1] = new int[20];jagged2D[9] = new int[100];
jagged2D[0][0] = 1;jagged2D[9][99] = 100;
Namespace != Assembly
• Orthogonal concepts:– namespace for organization– assembly for packaging
• One namespace could be spread across multiple assemblies
• One assembly may contain multiple namesspaces – e.g. mscorlib.dll
Programming in .NET Destructors and Finalize
• Destructors are used by some object-oriented systems to clean up objects just before they're destroyed
• The Finalize method is called automatically just before an object is garbage collected
• Example:public class Person {
public int age; ~Person() {// clean up non-memory resources}
}• Do not use - unless non-memory resource