namrathakalasannavar955210856.files.wordpress.com.…  · web view.net framework is an essential...

237
1 Chapter 1 Getting started with .Net Framework 4.0 GETTING STARTED WITH .NET FRAMEWORK 4.0 .NET Framework is an essential component of the Windows operating system, which helps in creating applications by integrating different programming languages, such as C#, Visual Basic, J#, and Visual C++. This framework consists of a virtual execution system called the Common Language Runtime (CLR) and a set of class libraries. CLR is a Microsoft product of the common creating execution and development environments in which languages and libraries work together. 1.1 Benefits of .NET Framework: The following are the benefits of .NET Framework: Consistent Programming Model: Provides a consistent object- oriented programming model across different language. You can use this model to create programs for performing different tasks, such as connecting to and retrieving data from databases, and reading and writing in files. Cross-Platform Support: Specifies that any windows platform that supports CLR can execute .NET application, that is, .NET application enables interoperability between multiple Windows operating systems. Language Interoperability: Enables code written in different languages to interact with each other. This allows reusability of code and improves the efficiency of the development process. Example: In an ASP.NET application created using Visual Basic language, you can inherit a C# class in the application. The CLR has a built-in support for language interoperability. Prepared By Namratha K

Upload: others

Post on 13-Jun-2021

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

1

Chapter 1 Getting started with .Net Framework 4.0

GETTING STARTED WITH .NET FRAMEWORK 4.0

.NET Framework is an essential component of the Windows operating system, which helps in creating applications by integrating different programming languages, such as C#, Visual Basic, J#, and Visual C++. This framework consists of a virtual execution system called the Common Language Runtime (CLR) and a set of class libraries. CLR is a Microsoft product of the common creating execution and development environments in which languages and libraries work together.

1.1 Benefits of .NET Framework:

The following are the benefits of .NET Framework:

Consistent Programming Model: Provides a consistent object-oriented programming model across different language. You can use this model to create programs for performing different tasks, such as connecting to and retrieving data from databases, and reading and writing in files.

Cross-Platform Support: Specifies that any windows platform that supports CLR can execute.NET application, that is, .NET application enables interoperability between multiple Windows operating systems.

Language Interoperability: Enables code written in different languages to interact with each other. This allows reusability of code and improves the efficiency of the development process.

Example: In an ASP.NET application created using Visual Basic language, you can inherit a C# class in the application. The CLR has a built-in support for language interoperability.

Automatic Management of Resource: Specifies that in .NET, you do not need to manually free the application resources, such as files, memory, network, and database connection. .NET Framework provides a feature called CLR that automatically tracks the resource usage and helps you in performing the task of manual resource management.

Ease of Deployment: Specifies that the .NET Framework installs applications or components that do not affect the existing applications. In most cases, to install an application, you need to copy the application along with its components on the target computer. In .NET, applications are deployed in the form of assemblies. Therefore, registry entries are not required to store information about components and applications. Therefore, the version problem is also eliminated in .NET Framework.

Prepared By Namratha K

Page 2: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

2

Chapter 1 Getting Started With .Net Framework 4.0

1.2 Architecture of .NET Framework 4.0:

The latest version of .NET provides a framework that helps in developing portable, scalable, and robust applications. The applications developed in .NET Framework 4.0 can be executed in a distributed environment. Therefore, you can say that the .NET Framework 4.0 is designed to address the latest needs of the developers.

The architecture of .NET Framework 4.0 mainly consists of components of .NET Framework 2.0 and 3.0 with few enhancements as shown in below figure.

1.3 Components of .NET Framework:

The .NET Framework provides the help to developers create new application. It provides all the necessary components to develop and run .NET-based programs on your system. The components of .NET Framework 4.0 architecture are as follows:

Prepared By Namratha K

Page 3: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

3

Chapter 1 Getting Started With .Net Framework 4.0

Common Language Runtime (CLR) Common Type System (CTS) Metadata and Assemblies

.NET Framework class library Windows Forms

ASP.NET and ASP.NET AJAX ADO.NET

Windows Workflow Foundation Windows Presentation Foundation Windows Communication Foundation Windows CardSpaceLINQ

1.3.1 Common Language Runtime (CLR):

CLR is an Execution Engine for .NET Framework application and is one of the most important components of .NET Framework, provides a run-time environment to run the code and provides various services to develop the application easily.

The services provided by CLR are – Memory Management

Thread execution

Code safety

Exception Handling Code execution Verification Debugging Language Integration Compilation Security

Automatic Memory Management: CLR manage the allocation and de-allocation memory automatically by using various built-in function. Therefore programmer need not write the code to explicitly allocate and de-allocate memory to programs. This automatic memory management resolves the issues of memory leaks and invalid memory references.

Garbage Collection: It is play an important role in CLR to prevent memory leaks during execution of programs. The Garbage collection automatically releases the memory when it is not being used.

Code Access Security (CAS): It is the CLR’s security system that enforce security policies by preventing unauthorized access to protected resource and operations. CAS also helps in making

the code robust, which implies that it makes the code robust, which implies that it makes the code extensible and reusable.Prepared By Namratha K

Page 4: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

4

Prepared By Namratha K

Page 5: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

5

Chapter 1 Getting Started With .Net Framework 4.0

Code Verifications: CLR imposes type safety and prevents the source code from performing illegal operations, such as accessing invalid memory locations.

The following figure shows the process of compilation and execution of the code by the JIT Compiler:

Fig 1.2: Compilation and Execution of the code

When you compile your source code by selecting .NET aware compilers such as Visual Basic, C#, Visual C++, J#, or any of the third party compilers, such as COBOL, Perl or Eiffel. The compiler converts source code in to IL / MSIL / CIL, which is CPU independent and the required metadata is generated. The metadata contains the definition of types, member signature, the members in the code, and other details that the code uses at the time of execution. After compiling, the code is passed to the CLR at the runtime to a verification process that examines the IL and metadata to check whether the code is safe, such as it should be able to access only those memory locations which it is authorized to access. CLR uses the rules to examine the code which are stated in the CLS and CTS. After verifying, a JIT [Just-In-Time] compiler extracts the metadata from the file to translate that verified IL code into CPU-specific code or native code. These type of IL Code is called as managed code.

The source code which is directly compiles to the machine code and runs on the machine where it has been compiled such a code called as unmanaged code. It does not have any services of CLR.

Managed Code: Managed code is the code that is executed directly by the CLR. The applications that are created using managed code automatically have CLR services, such as type checking, security, and automatic garbage collection.The process of executing a piece of managed code is as follows:

Prepared By Namratha K

Page 6: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

6

Prepared By Namratha K

Page 7: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

7

Chapter 1 Getting Started With .Net Framework 4.0

Selecting a language compilerCompiling the code to IL[This intermediate language is called managed code] Compiling IL to native codeExecuting the code

Unmanaged Code: Unmanaged Code directly compiles to the machine code and runs on the machine where it has been compiled. It does not have services, such as security or memory management, which are provided by the runtime. If your code is not security-prone, it can be directly interpreted by any user, which can prove harmful.

Memory Management: One of the most important services that the CLR provides during managed execution is the automatic memory management. The CLR uses the garbage collector to manage the allocation and release of memory for an application.

It is one of the advantages of CLR that is for the developers since it reduces the burden of writing codes to manage memory while developing managed applications. Automatic memory management removes common problems, such as forgetting to free an object which results in memory leak, or attempting to access memory for an object that is already free.

1.3.2 Common Type Systems [CTS]:

The CTS defines the rules for declaring, using, and managing types at runtime. It is an integral part of the runtime for supporting cross-language communication.

The common type system performs the following functions:

Enables cross-language integration, type safety, and high-performance code execution. Provides an object-oriented model for implementation of many programming languages.Defines rules that every language must follow which runs under .NET framework like C#, VB.NET, F# etc. can interact with each other.

The CTS can be classified into two data types, are

Value TypesReference Types

The base class of all the types is the System.Object class. The hierarchy of the types as shown below:

Prepared By Namratha K

Page 8: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

8

Prepared By Namratha K

Page 9: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

9

Chapter 1 Getting Started With .Net Framework 4.0

Fig 1.3: hierarchy of value type and reference type

The following table shows some of the differences between values types and reference types.

Value Types Reference TypesAllocated on stack Allocated on heap

variable contains the data itself variable contains the address of memory location wheredata is actually stored

When we copy a value type variable to When copying a reference type variable to anotheranother one, the actual data is copied variable, only the memory address is copied. Bothand each variable can be independently variables will still point to the same memory location,

manipulated. which means, if we change one variable, the value willbe changed for the other variable too.

Integer, float, boolean, double etc are string and object are reference types.value types.Derived from System.ValueType Derived from System.Object

1.3.3 Common Language Systems [CLS]

The Common Language Specification (CLS) is a set of rules that a given .NET-aware compiler must support to produce code that can be hosted by the CLR, while at the same time be accessed

Prepared By Namratha K

Page 10: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

10

Chapter 1 Getting Started With .Net Framework 4.0

in a uniform manner by all languages that target the .NET platform. In many ways, the CLS can be viewed as a subset of the full functionality defined by the CTS.

The CLS helps enhance and ensure language interoperability by defining a set of features that developers can rely on to be available in a wide variety of languages. The classes that follow the rules specified by CLS are termed as CLS-complaint classes. The classes defined in the .NET

Framework class library are CLS-Compliant. The CLS describes a set of features that different languages have in common. CLS Compliance is especially important when creating software components that will be used by other languages.

The most important rules, and which apply to public and protected members are

i. All types appearing in a method prototype must be CLS-compliant ii. Array elements must have a CLS-compliant element type. Arrays must also be 0-

indexed iii. A CLS compliant class must inherit from a CLS-compliant class only

1.4 Metadata and Assemblies

A metadata is binary information that describes your program, stored in a CLR Portable Executable (PE) file or the memory.

The metadata contains the following:

Assembly information, which includes the metadata identity that can be name, version, culture, public key, the types of assemblies, other reference assemblies, and security permissions.

Information about types, such as name, visibility, base class, interfaces used, and members (methods, fields, properties, events, and nested types)

Attribute information that modifies the types and members of a class.

An assembly contains a self-describing binary file that can be either Dynamic Link Library (DLL) or Executable (EXE). It also contains a collection of types, such as classes, interfaces and structures.

There are two types of assembly:

Prepared By Namratha K

Page 11: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

11

Prepared By Namratha K

Page 12: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

12

Chapter 1 Getting Started With .Net Framework 4.0

i. Single file assembly : Single assembly can contain multiple code files of single code file can have more than one assembly. It contains the type information and implementation as well as the assembly’s manifest into a single physical file.

Example: Class Libraries, Windows Forms / WPF applications, Console applications and Windows Services

ii. Multi-file assembly:

An assembly can consist of one or more files called modules. Exactly one of these modules contains the assembly manifest.

Note that the files in a multi-file assembly can reside in separate locations and are linked together with the assembly manifest. Multi-file assemblies are rare, and Visual Studio doesn’t directly support their creation. The most common reason for multi-file assemblies is when a single assembly combines code from multiple programming languages.

Assemblies can be two types:

Static assemblies: Static assemblies include interfaces, classes and resources. These assemblies are stored in PE (Portable executable) files on a disk.

Dynamic assemblies: Dynamic assemblies run directly from the memory without being saved to disk before execution. However, after execution you can save the dynamic assemblies on the disk.

1.4.1 Assembly Content:

Assembly is a logical unit that consists of 4 elements as follows:

ManifestMetadataIL code(static or dynamic)Set of resources[bitmaps, jpeg]

Assembly manifest: Assembly contains data that describes how elements are related to each other within the assembly. The manifest, also known as assembly manifest, contains the assembly metadata needed for providing the assembly’s version requirements and security identity. The manifest can be stored either in a PE file with IL code or in a standalone PE file that contains only the manifest information. The list of information listed below

Prepared By Namratha K

Page 13: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

13

Chapter 1 Getting Started With .Net Framework 4.0

Table1.1: Information stored in the assembly manifest

Information DescriptionAssembly name Specifies the name of the assembly

Indicates a major version number, a minor version number, and a revisionVersion number and build number. The CLR uses these numbers to enforce the version

policy.

CultureProvides information about the culture or language that the assemblysupports.

Strong name Indicates a public key from the publisher if the assembly contains ainformation strong nameList of all files in Contains an alphanumeric string that is generate as per the contents of athe assembly file (hash) of each file contained in the assembly and a file name.

Type referenceContains the information required to map a type reference to the file thatcontains its declaration and implementation. Types exported from the

informationassembly use the type reference information.Provides the list of assemblies, which are usedas a reference by the

Information on assembly. The reference of assembly containsthe whole details ofreferenced dependent assembly, such as name, assembly metadata and public key, ifassemblies

the assembly is strong named.

1.4.2 Global Assembly Cache:The Global Assembly Cache (GAC) is a folder in Windows directory to store the .NET assemblies that are specifically designated to be shared by all applications executed on a system.

One thing to remember is that the assemblies must be sharable by registering them in the GAC, only when needed; otherwise, they must be kept private. Each assembly is accessed globally without any conflict by identifying its name, version, architecture, culture and public key.

Further, it is not mandatory to install the assemblies in the GAC to make them accessible to the COM interop or unmanaged code, where COM interop is a service that enables .NET Framework objects to communicate with COM objects.

You can deploy an assembly in GAC by using any one of the following: An installer that is designed to work with the GACThe GAC tool known as Gacutil.exeThe Windows Explorer to drag assemblies into the cache.

1.4.3 Strong Name Assembly:A Strong Name contains the assembly’s identity, that is, the information about the assembly’s name, version number, architecture, culture and public key.

Prepared By Namratha K

Page 14: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

14

Chapter 1 Getting Started With .Net Framework 4.0

Using Microsoft Visual Studio .NET and other tools, you can provide a strong name to an assembly. By providing strong names to the assembly, you can ensure that assembly is globally unique.

Benefits:

1) Provides uniqueness to the names by generating a private key. 2) Ensures that a version of the assembly you are using comes from the same publisher that

created the version the application was built with 3) Facilitates integrity check, which ensures that the contents of the assembly do not change

since its last build.

1.4.4 Private and Shared Assembly:

A single application uses an assembly, then it is called as a private assembly.

Example: If you have created a DLL assembly containing information about your business logic, then the DLL can be used by your client application only. Therefore, to run the application, the DLL must be included in the same folder in which the client application has been installed. This makes the assembly private to your application.

Assemblies that are placed in the Global Assembly cache so that they can be used by multiple applications, then it is called as a shared assembly.

Example: Suppose the DLL needs to be reused in different applications. In this scenario, instead of downloading a copy of the DLL to each and every client application, the DLL can be placed in the global assembly cache by using the Gacutil.exe tool, from where the application can be accessed by any client application.

1.4.5 Side-by-Side Execution Assembly:

The process of executing multiple versions of an application or an assembly is known as side-by-side execution. Support for side-by-side storage and execution of different versions of the same assembly is an integral part of creating a strong name for an assembly.

Strong naming of .NET assembly is used to provide unique assembly identity by using the sn.exe command utility.

The strong-named assembly’s version number is a part of its identity, the runtime can store multiple versions of the same assembly in the GAC.Load these assemblies at runtime.

Prepared By Namratha K

Page 15: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

15

Chapter 1 Getting Started With .Net Framework 4.0

1.5 .NET Framework Class Library:

The .NET Framework includes classes, interfaces, and value types that helps in speeding up the application development process and provide access to system functionality. To facilitate interoperability between languages, most .NET Framework types are CLS-compliant and can be used from any programming language whose compiler conforms to the common language specification (CLS).

The .NET Framework types are the foundation on which .NET applications, components, and controls are built. These entities perform the following functions:

Represent base data types and exceptions Encapsulate data structuresPerform I/OAccess information about loaded types Invoke .NET Framework security checksProvide data access, rich client-side GUI, and server-controlled, client-side GUI

The .NET Framework Class Library (FCL) is a library consisting of namespaces, classes, interfaces, and data types included in the .NET Framework. This library is organized into namespaces that contain functionally related groups of classes. These namespaces are divided among different categories, such as data access, common types, debugging, file access, network communication, security, Windows applications, Web applications, Web services, XML data etc. The following points need to be remembered while using the FCL:

The classes, interfaces, structures, and enumerated values are collectively referred to as types.

The different types in the framework are arranged in a hierarchy of namespaces. Namespaces are arranged a hierarchy that has words separated by Dots (.).Example: System.IO.Stream, System.Windows.Forms.Form respectively

The System namespace is a parent of all the types available in the .NET Framework Class Library.Example: System namespace contains base data type’s classes, such as Object, Int,Array, and Short.

All types must have a base class. The exception to this rule is the System.Object type, which acts as the base type for all types in .NET Framework. This implies the compiler explicitly declares its base class to the Object class.

Prepared By Namratha K

Page 16: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

16

Chapter 1 Getting Started With .Net Framework 4.0

1.5.1 Windows Forms (WF):Windows forms is the graphical representation of any window displayed in an application. It is included as a part of Microsoft’s .NET Framework. You can create an application using Window

Forms in any CLR supported language. A Windows Form is used to either accept input from or display information to the user. In Windows Forms, you add controls to the forms and raise events, such as mouse-click, which is handled by event handlers in an application.

1.5.2 ASP.NET and ASP.NET AJAX:

ASP.NET is a web development mode, which is used to deliver interactive and data-driven web application over the internet. It also consists of a large number of controls, such as text boxes, buttons, and labels for assembling, configuring, and manipulating code to create Hyper Text Markup Language (HTML).

1.5.3 Advantages of ASP.NET:

Better Performance: Specifies that when you request a web page for the first time after compiling ASP.NET code, the CLR compiles the code and stores the cached copy of the result. Now, for any subsequent calls to the same page, the cached copy of the result is retrieved instead of going back to the server.

Improved Security: Refers to the different methods of authentication included in ASP.NET:

Forms: Allows the ASP.NET application to use its own custom business logic for authentication.

Windows: Checks the identity of a user against the Windows user accounts that are stored on the Web Server. If the credentials of a user match with that of a Windows user account, then the user is authenticated.

Greater Scalability: Specifies that the session states in ASP.NET are maintained in a separate process on a different machine or database. This enables cross-server sessions to occur, solving the problem of web forms when more web servers need to be added as the traffic grows.

Cookie-less Sessions: Specifies that ASP.NET stores the session even when the cookies in a Web browser are disabled. In such a case, the session ID is passed as a part of the Uniforms Resource Locator (URL).

AJAX: which is also known as Atlas, is used as an extension for ASP.NET to develop and implement the AJAX functionality. ASP.NET AJAX has both side client and server components to develop

Prepared By Namratha K

Page 17: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

17

Prepared By Namratha K

Page 18: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

18

Chapter 1 Getting Started With .Net Framework 4.0

the Web applications, which can update the information on a Web application without reloading the page completely.

Advantages of using AJAX:

Asynchronous: Enables asynchronous calls to the Web server without making the users wait for the

data.

Minimal transfer of data: Helps in sending only a part of the modified data to the web server to minimize the network traffic and perform the operations quicker.

Minimal processing on the Web server: Minimizes the processing on the Web server as only the necessary data needs to be sent. Now, the server is not required to send a full page back to the user.

Context: Reduces burden on the server by sending a request back to the server through theclient-side script. AJAX-based applications implement partial page post backs instead of full page post backs, which reduce the data traffic between the client and server.

1.6 ADO.NET:

ADO.NET is a technology used for working with data and databases of all types. It provides access to data sources, such as Microsoft SQL Server, data sources exposed through OLE DB, and Extensible Markup Language (XML).You can use ADO.NET too connect to data sources for retrieving, manipulating, and updating data.

Advantages:

Disconnected Data Architecture: Implies that applications connect to the database only when data needs to be retrieved or modified. After the database operation has been performed, the connection to the database is closed. To perform any database operation again, the connection with the database will have to be re-established.

Cached Data in Datasets: Follows a disconnected architecture for accessing or modifying data. It is not required for the applications to connect to the database for processing each record. Therefore, the data is accessed and later stored in the datasets. A dataset is a cached set of database records, which is independent of data source. Even when you are disconnected from the database on which you are working, you can make modifications in the database.

Prepared By Namratha K

Page 19: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

19

Chapter 1 Getting Started With .Net Framework 4.0

Scalability: Reduces the traffic on the database and saves the resources to make the database more efficient in meeting the demands of the user. ADO.NET help in attaining scalability while working with datasets. All database operations are performed on the dataset instead of on the database.

Transfer of Data in XML Format: Transfers data from a database into a dataset and from the dataset to another components using XML, which is the standard format used for transferring data in ADO.NET. You can also use an XML file as a data source and store the data from it into a dataset. One need not know XML since data conversion from and to XML is abstracted from

the user.

Interaction with the Database through Data Commands: Specifies that database operations are performed by executing the data commands. All operations on database, such as retrieving, modifying, or updating of data are performed using data commands. A data command is either a Structured Query Language (SQL) statement or a stored procedure.

1.7 Windows Workflow Foundation

WF is a technology introduced by Microsoft, which provides a programming model for building workflow based applications on Windows. It includes activities, workflow runtime, workflow designer, and a rules engine. WF is a part of .NET Framework 3.0, 3.5 and 4.0.

Feature

Activities: Receives some parameters from the developer, execute the actions specified in the parameters, and then the flow is transferred to the next activity.

Example: The code for ifelse activities.

Workflow Designer: Designs workflows by placing activities within the workflow model. One interesting feature is that it can be re-hosted within any Windows Forms application.

Workflow Runtime: Executes the activities in a workflow. It is a lightweight and extensible engine that resides within a .NET process, facilitating the developers to bring workflow to anything from a Windows Forms application to an ASP.NET website or a Windows Service.

Rules Engine: Enables declarative, rule-based development for workflows and any .NET application to be used.

The architecture of WF is shown below:

Prepared By Namratha K

Page 20: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

20

Chapter 1 Getting Started With .Net Framework 4.0

Fig 1.6: Windows Workflow Foundation Architecture

There are 3 layers:Model Layer: The top layer is model layer where the developers build their code to run in the

workflow. This layer provides the developer to following activities:

Add built-in activities Create Custom activities Building rules and workflows

Runtime Layer: The second layer is runtime layer. It ensures that the processes, such as execution of rules, tracking and scheduling and managing state lifecycle and activation, take place.

Hosting Layer: The last layer is hosting layer, which connects the engine and the process that is being executed. It also provides a set of services, such as persistence, timer, tracking, communication, transactions, and threading, required for managing and controlling the workflow. WF also contains built-in services that provide the interfaces required to work with.NET Framework 2.0 and its advanced versions.

Prepared By Namratha K

Page 21: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

21

Chapter 1 Getting Started With .Net Framework 4.0

1.8 Windows Presentation Foundation (WPF):

WPF provides the base for building applications and a clear separation between the user interface and the business logic. WPF helps in building interfaces that include documents, media, two or three dimensional graphics, animations and web-like characteristics. The architecture of WPF shown below:

Fig 1.7: Architecture of WPF

WPF provides document services, such as XML Paper Specification (XPS) documents and packaging services.

XPS documents are shown with an XML-based schema that defines the layout and visual appearance of a page.

The WPF namespace System.IO.Packaging helps in organizing data, content, and resources of your application into a single, portable, easy to access, and distributable .zip document.

WPF aims at unifying several user interface services, such as application services, controls layout, data-binding and deployment services. It provides shape for 2-D graphics by providingin-built brushes, pens, and geometries.

WPF supports various video formats, such as Windows Media video (WMV), Moving Picture Experts Group (MPEG), and some Audio Video Interleave (AVI) files. It also supports audio files, some common image formats and animations.Prepared By Namratha K

Page 22: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

22

Prepared By Namratha K

Page 23: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

23

Chapter 1 Getting Started With .Net Framework 4.0

WPF provides some basic services, such as accepting input and raising events, property system, and accessibility.

1.9 Windows Communication Foundation:

WCF is one of the new technologies introduced by Microsoft in .NET Framework 3.0 for building and running connected systems. It is a service-oriented technology for developing applications in a distributed system that provides services to the client applications. WCF is simply an enhanced technology for providing the same functions in a better way.

The enhancements of WCF as compared to the previous technologies are as follows:

1) Merges technologies, such as Web services, remoting, distributed transactions, and message queuing in one place and reduces development time.

2) Consists of many powerful enterprise features 3) Integrates easily with other technologies and consequently, enables greater interoperability.

The WCF Architecture is composed of the following five layers:

Application: Represents the location of the application.

Contracts: Consists of services, data and message contracts as well as bindings and policies. The contracts layer gives you information about the different features of the message system [which involves sending and receiving the messages from one end to another].

Service Runtime: Gives information about the different behaviours that take place at runtime. This layers loads all the services.

Messaging: Gives information about different channels that are required at the time of processing a message. This layer deals with the message content that needs to be communicated.

Prepared By Namratha K

Page 24: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

24

Chapter 1 Getting Started With .Net Framework 4.0

Fig 1.8: Architecture of WCF

Activation and Hosting: This layer deals any service can be hosted using the Internet Information Services (IIS) or Windows Activation Service.

The WCF programming model combines Web Services, .NET remoting, distributed transactions, and message queues into a single service-oriented programming model for distributed computing.

1.10 Windows CardSpace:

Windows CardSpace is a client software provided by Microsoft that improves the safety of accessing resources and helps in sharing personal information on the internet. It helps programmers in developing websites and software that are less prone to identity-related attacks, such as phishing.

Advantages:Prepared By Namratha K

Page 25: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

25

Prepared By Namratha K

Page 26: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

26

Chapter 1 Getting Started With .Net Framework 4.0

1) Reducing the problems of traditional online security mechanisms by relying on separate desktop and cryptographically strong authentication rather than on user names and passwords.

2) It facilitates secure online transactions, such as online shopping, banking, and bill payment.

3) You can create a card using the WCS utility that comes with .NET 4.0 as shown below Windows CardSpace user interface:

WCS is based on the identity meta system. This system allows you to use different digital identities across different platforms. There are two types of cards available:

Personal Cards: Refers to the card that is based on the self-issued identity providers

Managed Cards: Refers to the card that is based on identity providers provided by vendors other than Microsoft.

Suppose a CardSpace enabled site wants to retrieve the personal information of the user (identifies) and for that demands a particular type of card. The CardSpace then stored identifies as virtual information card. The user selects the card to use the CardSpace software contacts the identity provider to get the digitally signed token that contains the required information. WCS is built with an open set of XML-based protocols, which includes WS-Security, XS-MetadataExchange, and WS-SecurityPolicy. With these set of protocols, any technology or platform can integrate with the CardSpace.

The overall process of CardSpace contains issuing, acquiring and using digital identifies that can be defined by the following three distinct roles:

User – refers to an entity containing a digital identity.

Identity Provider – refers to a provider that provides a digital identity to the user. The digital identity is used to provide information about the username and password of the user. Digital identifies created by the identity providers may contain different information and provide different levels of assurance to identify the actual user.

Relying Party – refers to an application that relies on a digital identity. It can use an identity to authenticate a user and then make authorization decision, such as allowing or disallowing the user to access information.

1.11 LINQ:

LINQ is an acronym for Language Integrated Query, which is one of the components of .NET Framework 4.0 that adds native data querying capabilities to .NET languages by using syntax similar to SQL.The following are simple LINQ query in different language:

Visual Basic

Prepared By Namratha K

Page 27: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

27

Prepared By Namratha K

Page 28: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

28

Chapter 1 Getting Started With .Net Framework 4.0

Dim query = From s In Students Where s.Gender = “M” Select s.Name

C#

var query = from s in Student where s.Gender = “M”; select s.Name;

When you execute the preceding query, it returns the names of all the male students and is stored in the variable query.To print that list, you have to write the following lines of code:

In the preceding code, you can find that the syntax of the query is similar to the SQL, which we normally follow for accessing relational data. It is important to note that even if it looks similar to SQL, the LINQ query displayed is not an SQL statement. Instead, it is purely in C# language.

LINQ queries resemble SQL, they are not restricted to accessing only relational databases. LINQ enabled data access components are as follows:

LINQ to ADO.NET:- Includes two options, LINQ to SQL, which translates a query into an SQL query, and then issues it against the tables specified in the query in an SQL Server database, and LINQ to DataSet, which executes a query on the contents of a DataSet.

LINQ to Object:- Allows querying objects in a collection. LINQ to Objects is not dynamic. After creating and using the result set, any changes made to the source collection do not automatically update the result set.

LINQ to XML:- Allows querying of XML data. In addition, it helps in creating and manipulating XML data. This option has a different syntax; however, the basic LINQ query remains the same.

Prepared By Namratha K

Page 29: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

29

Chapter 1 Getting Started With .Net Framework 4.0

Assignment

1) What are the functions of CTS? Display hierarchical representation of different data types.

2) What is an assembly manifest? What is the information stored in assembly manifest?3) Explain windows workflow foundation architecture with a neat diagram.4) Explain the architecture and components of .NET framework.5) Short note on: Private Assemblies, Shared Assemblies6) Explain how CLR host an application in .NET platform. Give the block diagram.

Prepared By Namratha K

Page 30: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

30

Chapter 2 Introducing C#

Introducing C#

2.1 Need of C#:

C# is one of the intermediate programming languages used to create executable program. It is an object-oriented programming language having many similarities to java, C++ and Visual Basic. Being an object-oriented programming language, it fully supports the concepts of encapsulation, inheritance, and polymorphism. In addition to these features, C# has various other features, such as Language-Integrated Query (LINQ), delegates and lambda expressions. These features are listed as follows:

Flexible – C# programs are capable to execute on the local system, any remote system, on the web. Powerful – C# is able to create any type of applications, word processors, spreadsheets and compilers Easy to use – use of simpler code statements instead of using complex data types and operators

Visually oriented – Allow you to use the .NET code libraries for developing complicated and attractive

User Interfaces.

Secure – Enables you to protect your code and data from unwanted

2.2 The Anatomy of a Simple C# Program

A class declaration in C# is composed of attributes, modifiers, the class name, base class and interfaces, and a body. Attributes, modifiers, and bases are all optional.Syntax:

class C {... fields, constants ... // for object-oriented programming... methods ...... constructors, destructors ...... properties ...// for component-based programming... events ...... indexers ... // for convenience... overloaded operators ...... nested types (classes, interfaces, structs, enums, delegates)

}

The body of the class contains class members that can include constants, fields (or variables), methods, properties, indexers, events, operators, and nested types. Nested types are defined by

Prepared By Namratha K

Page 31: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

31

class, interface, delegate, struct, or enum declarations within the class body.

C# program can be written as follows below:

Prepared By Namratha K

Page 32: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

32

Chapter 2 Introducing C#

using System;

class HelloClass {

public static int Main(string[] args){

Console.WriteLine("Hello World!");

Console.ReadLine();

return 0;

}

}

It is declared inside a class. It must be static and it should not be public. C# executable program must include the Main() method in any one of the classes. public: is an access modifier that tells the main method is accessible by anyone. static: the Main method is a global one and can be called without creating an instance of the class. void: is a type modifier, that the Main method does not return any value. string[] args: method has single parameter which happens to be an array of strings and also contain any

number of incoming command – line – arguments.

Rules to use members: All the keywords are in the lowercase ex: public, global, private and so on. All the namespaces, types and member names begin with an initial capital letter and have capitalized by embedded

words ex: Console, WriteLine, MessageBox, System

Variation on the Main() method:

Like in C or C++, the execution of C# program begins with Main method. In C#, we are having four overloaded forms of Main method.

When a program starts, it looks for an entry point. This is the role of the Main() method. In fact, a program, that isan executable program, starts by, and stops with, the Main() method. They are...

i. public static void Main(string[] args) //No Return Type and String Arguments{ //body}

ii. public static void Main() //No Return Type and No Arguments{

//bodyPrepared By Namratha K

Page 33: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

33

}

iii. public static int Main(string[] args) //Integer Return Type and String Arguments {

Chapter 2 Introducing C#

//body }

iv. public static int Main() //Integer Return Type and No Arguments{ //body}

2.3 C# Pre-processor Directives:

In C# there is no separate preprocessing step and therefore the term preprocessor directive that help you to interact with the compilation process.

The preprocessor directive allow you to

Conditionally skip sections of the sources Report errors & warning conditions Define distinct regions of source code

A preprocessor directive must be the only instruction on a line.

Syntax: # directive name or # Identifier

Where, start with ‘#’ and is followed by an identifier that is the directive name.

C# includes the following pre-processor directives:

Table 2.1: Lists of Preprocessor Directives available in C#

Directive Names Meaning

#define & #undefDefine and undefined the conditional compilation symbols, respectively.

#if, #else, #elif, #endif Allow you to conditionally skip sections of source code.

#lineHelps you to control line number emitted for errors and warnings

#error & #warning Issues errors and warnings, respectively#region & Allow you to explicitly mark sections of source code.

Prepared By Namratha K

Page 34: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

34

#endregion

Prepared By Namratha K

Page 35: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

35

Chapter 2 Introducing C#

Example

#define TEST using System;

namespace Examples{

class ExPreD{

static void Main(string[] args){

#if (TEST)Console.Write("TEST

is defined"); #elseConsole .Write ("Test is

not defined"); #endifConsole.Read();

}}

}

2.4 Identifiers and Keywords:

In C#, an Identifiers is a sequence of character used to identify a variable, constant, or any user-defined programming element.

Rules:

Starts with a letter or an underscore and ends with a character.

Can have letters, digits and underscores

Must not be a reserved word

Must be a complete word without any blank spaces.

Example: sum, SUM, _sum, . . . . . .

Keywords are the reserved words whose meanings are predefined to the C# compiler.

Rules:

You cannot use keywords as variable, methods and properties

If you want to use the keywords as identifiers, prefix the keyword with @ character.

Prepared By Namratha K

Page 36: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

36

Chapter 2 Introducing C#

Table 2.2: Lists of Reserved keywords available in C#Reserved Keywordsabstract as base bool break byte case this ObjectCatch char checked class const continue decimal is SizeofDefault delegate do double else enum event out ReadonlyExtern false finally fixed float for if param Using

foreach goto int public protected private shortnamespace

unchecked

2.5 Data Types, Variables and Constants:

The C# language provides a rich set of built-in data types.

Points:

All variables, whether user-defined or built-in (intrinsic), can be used as objects anywhere in a program,

All variables in a program are automatically initialized to default values by the system when they are declared.

C# variables are categorized in to three:

i. Value Types: which include all numerical data types (int, float, etc.), as well as enumerations and structures, are allocated on the stack.

ii. Reference Types: which include reference of an objects, are allocated on the heap.

iii. Pointer Types: which holds the memory address of a variable.

The Value types and Reference types in C# are divided into different categories that as shown below:

Prepared By Namratha K

Page 37: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

37

Figure 2.1: Shows different types of value types and reference types

Chapter 2 Introducing C#

2.5.1 Value Types:

Allow you to store the data directly into the variable. They are derived from System.ValueType. The value type and their content are stored at the same location memory. The default values of value types are stored on stack.

Table2.3: Lists the available Primitive types in C# 2010. Type Represents Ranges Default

Bool A Boolean value True or False FalseByte 8-bit unsigned integer type 0 to 255 0

Char Single 16-bit Unicode character U +0000 to U +ffff '\0'128-bit precise decimal values with 28-29 (-7.9 x 1028 to 7.9 x 1028) / 100 to

28decimal significant digits(16 bytes) 0.0M

double64-bit double-precision floating point type(8 bytes)

(+/-)5.0 x 10-324 to (+/-)1.7 x 10308

0.0D

float32-bit single-precision floating point type(4 bytes) -3.4 x 1038 to + 3.4 x 1038

0.0FInt 32-bit signed integer type(4 bytes) -2,147,483,648 to 2,147,483,647 0

Long 64-bit signed integer type(8 bytes) -9,223,372,036,854,775, 808 to 0L9,223,372,036,854,775,807sbyte 8-bit signed integer type -128 to 127 0

short 16-bit signed integer type(2 bytes) -32,768 to 32,767 0

Uint 32-bit unsigned integer type 0 to 4,294,967,295 0

ulong 64-bit unsigned integer type(8 bytes)0 to 18,446,744,073,709,551,615 0

ushort 16-bit unsigned integer type 0 to 65,535 0

Int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0

Example 3:

using System;

namespace Class_Demos{

class TypeMaxMin{

static void Main(){

Prepared By Namratha K

Page 38: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

38

Console.WriteLine("System Minimum"); Console.WriteLine("MinValue of sbyte{0}", sbyte.MinValue); Console.WriteLine("System Maximum"); Console.WriteLine("MaxValue of sbyte{0}", sbyte.MaxValue); Console.ReadLine();

}}}

Prepared By Namratha K

Page 39: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

39

Chapter 2 Introducing C#

2.5.1.1 Struct Type:

Struct types are a special form of classes having the properties of value types. As you know that the value type are stored on the stack, inherently the struct types are also stored on the stack. The struct can be copied and created efficiently, as stacks are the efficient and convenient means of storing and accessing the types.

You can create struct types by using the “struct” keyword. When you create a struct object and assign it to variable, the variable holds the value of the struct object.

[attributes] [modifiers] struct identifier [:interface]Example 4:

{Body;

}

You can apply only public, private and internal access modifiers to a struct and struct member definition. You cannot use the protected and protected internal access modifiers in structs because structs are implicitly sealed. This means that a struct cannot be a parent class of other classes.

The struct types are divided into the following 5 categories:

Integral Type: C# provides a set of basic data types which are known as integral types such as sbyte, byte,short, ushort, int, uint, long, ulong & char Floating-Point Type: It is divided into two types; they are, single and double floats.

Single float holds – is similar to the float data type, hold values up to 10308

.

Double float holds – is similar to the double data type, hold values up to 10308.

Decimal Type: It is equivalent to a long integer

Boolean Type: true or false

Nullable Type: when dealing with databases or when a user does not want to assign a value to a variable

of any data type.

2.5.1.2 Enum Type:

Enumerations are the user-defined integer data types that are declared using the “enum” keyword. You can define a set of named integral constants that can be assigned to a variable.

Example 5: Enum TrafficLignt{Red, Green, Yellow

};TrafficLight t1;t1=TrafficLight.Red;t2=TrafficLight.Green;t3=TrafficLight.Yellow;

Prepared By Namratha K

Page 40: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

40

To use the enumerated type, you need to declare a variable of the new enumeration type as t1. Now, TrafficLight enumeration can take any of the three values, Red, Green, and Yellow.

Prepared By Namratha K

Page 41: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

41

Chapter 2 Introducing C#

Example

using System;

namespace Class_Demos{

enum Color { Red=1, Green, Yellow} class EnumEx{

public static void Main(){

Console.WriteLine("Please select \n1. Red\n2. Grenn\n 3.Yellow");

int colopt =Int32.Parse(Console.ReadLine()); Color col=(Color)colopt;switch (col) { case

Color.Red:Console.WriteLine("The selected color is RED"); break;

case Color.Green:Console.WriteLine("The selected color is Green"); break;

case Color.Yellow:Console.WriteLine("The selected color is Yellow"); break;

}Console.Read();

}}

}

2.5.2 Reference Types:

C# also provides types that are passed by references to calling functions, known as reference types. Variables that refer to the objects store the reference of the actual data. The reference types use heap to store the references instead of the actual data.

Reference types can be categorized into 2 parts:

i. Pre-defined reference types: Dynamic type, Object type, String type

ii. User-defined reference types: Classes, Interfaces, Delegates, Arrays

Prepared By Namratha K

Page 42: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

42

Chapter 2 Introducing C#

Pre-defined reference types:

C# provides you some built-in reference types, which are as follows:

Dynamic type Object type

String type

Dynamic type:

You can store any type of value in the dynamic type variable. It performs the type checking of the dynamic type variable at run time.

Syntax: dynamic dyn=10;

Object type:You can assign values of any type to the variable of object type. It performs the type checking of the variable of object type at compile time.

Object type is base class for the other types such as value types, reference types, predefined types, user-defined types. The object type can be assigned a value of any other types, but requires the type conversion.

A value type converted to the object type, the process is known as

boxing An object type converted to the value type, the process is known as

unboxing

Example: object obj;obj = 100; // this is boxing

String type:It enables you to assign string values to the variables of string type. The string type is an alias for the System.String class. String type is directly derived from the object type. You cannot change its value.

The value for a string type can be assigned using the string literals in 2 forms: quoted and @quoted.

Example:string sname = “C# 2010”; @“C:\Windows\Microsoft.NET\Framework”

Where, @-Verbatim string literals: Stringliterals are embed escape charactersExample 7:

using System; namespace Class_Demos{

Prepared By Namratha K

Page 43: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

43

class StringEx{

Prepared By Namratha K

Page 44: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

44

Chapter 2 Introducing C#

public static void Main(){

string str="C# 2010";

Console.WriteLine("The variable value of str:" +str);

string str1=@"C:\Windows\Microsoft.NET\Framework";

Console.WriteLine("The variable value of str:" +str1);

Console.WriteLine("New string is " +str.Replace('C','J'));

Console.Read();

}

}

}ii. User-defined reference types:

C# provides you some user-defined reference types, which are as follows:

Classes Interfaces Delegates

Arrays

Classes:

All classes are user-defined data types and are considered as objects. All objects are derived from a singlebase class, known as System.Object. All C# console applications contain a single static method,called Main().

Example 8: class class_name{

static void Main(){

- - - - -}

}

Interface:

Interface define a set of functionalities that can be related to any class or struct. You cannot instantiate an object through an interface. Interface have method declarations, these are known as abstract ie., they do not have implementation part. A class that implements all the methods which is declared in the interface; otherwise, the compiler raise an error.Example 9: interface interface_name

{

Prepared By Namratha K

Page 45: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

45

Abstract method delcarations();- - - - - - - - }

Prepared By Namratha K

Page 46: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

46

Chapter 2 Introducing C#

Delegates:

A delegates is almost equivalent to function pointer in C++ or C. C# contains two kinds of objects – those that create a change and respond to the change.

A delegate acts as the tunnel between the two kinds of objects: Moving information from one side to another

C# delegates are class methods and can be either static or instance class methods.

A delegate can keep a track of its own state by maintaining information in the object to which it belongs. You can create a delegate by using delegate keyword, as shown below:

Example 10: public delegate int Intdelegate(int i);

using System; namespace Class_Demos{

public delegate int intDelgate(int a); class Calulator {

public static int SquareNum(int num){

return num * num;}

}class DelegatEx{

public static void Main(){

Console.WriteLine("Demonstrating Simple Delegate"); //Intializing and calling a delegate

intDelgate obj = new intDelgate(Calulator.SquareNum); Console.WriteLine("Value" + obj(2));Console.Read();

}}

}

Arrays:

An array is used to store the number of elements or variables of the same data type at contiguous memory locations in an ordered manner. Array cannot be created on the stack, but on the heap. This means you

Prepared By Namratha K

Page 47: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

47

cannot create an array statically in a method.

Prepared By Namratha K

Page 48: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

48

Chapter 2 Introducing C#

int x[10]; //create a static array of 10 elements

int[] x=new int[10];

int multiX[ , ] = new int[5,5]; //create an array of 5*5

Length Property: This property returns the total number of elements in an array.Example: int[ , ] a = new int[5,5];

Console.WriteLine(“Total no. of element:” +a.Length); //25

This is certainly useful because of this, you know the total size of the array, but determining the lower and upper bounds of an array is difficult. For this reasons, C# provides two other methods of the array class:GetLowerBound() and GetUpperBound().

NOTE: For all the data types, the base class is System.Object class.

Prepared By Namratha K

Page 49: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

49

Figure 2.2: Pictorial representation of all the data types

Prepared By Namratha K

Page 50: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

50

Chapter 2 Introducing C#

The following table shows some of the differences between values types and reference types.

Value Types Reference TypesAllocated on stack Allocated on heap

variable contains the data itself variable contains the address of memory location where data isactually stored

When we copy a value type variable toWhen copying a reference type variable to another variable, onlyanother one, the actual data is copied andthe memory address is copied. Both variables will still point to theeach variable can be independentlysame memory location, which means, if we change one variable,manipulated. the value will be changed for the other variable too.integer, float, boolean, double etc are value string and object are reference types.types.Derived from System.ValueType Derived from System.Object

The following are the differences between pointer type and reference type:

Both, pointer and references represent memory address but the difference is that,

References are tracked by the garbage collector and pointer are not.

You can perform arithmetic operations on pointers but not on references

The following are the differences between variable and constant:

Variable ConstantMemory location whose size depends on its data type. Are the fixed values assigned to a constant variables.The memory reserved for the variables of different Values remain unchanged throughout the execution ofdata types are different the program.Example : int i=10; Example : const float pie=3.14;

2.6 Type Conversions:While writing C# applications, you often need to perform a typical task; that is to convert one data type to another. For this type of conversion, type casting is used. Type casting has two forms:

Implicit

Explicit

2.6.1 Implicit Conversion:

Implicit conversions are the conversions that are performed by the compiler, in a type-safe manner.

Prepared By Namratha K

Page 51: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

51

Example: int i=123;

float f=i; //Converting an integer to a float implicitly

Table 2.4: List of Conversion methods

Method DescriptionToBoolean Converts types to a Boolean value, where possibleToByte Converts a type to a byte.

ToChar Converts a type to a single Unicode character, where possible.

ToDateTime Converts a type (integer or string type) to date-time structures.

ToDecimal Converts a floating point or integer type to a decimal type.ToDouble Converts a type to a double type.

ToInt16 Converts a type to a 16-bit integer.

ToInt32 Converts a type to a 32-bit integer.ToInt64 Converts a type to a 64-bit integer.

ToSbyte Converts a type to a signed byte type.

ToSingle Converts a type to a small floating point number.

ToString Converts a type to a string.ToType Converts a type to a specified type.

ToUInt16 Converts a type to an unsigned int type.

ToUInt32 Converts a type to an unsigned long type.ToUInt64 Converts a type to an unsigned big integer.

Example :

using System;

namespace Class_Demos{

class StringEx1{

public static void Main(){

int i = 75; string str = "12";Console.WriteLine(i.ToString());Console.WriteLine(Convert.ToInt32(str));Console.Read();

Prepared By Namratha K

Page 52: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

52

}}}

Prepared By Namratha K

Page 53: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

53

Chapter 2 Introducing C#

2.6.2 Explicit Conversion:

Table 2.5: Lists of implicit conversions followsFrom To

Prepared By Namratha K

Page 54: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

54

sbyte short, int, long, float, double , decimal

byte short, ushort, int, uint, long, ulong, float, double , decimal

short int, long, float, double , decimal

ushort int, uint, long, ulong, float, double , decimal

int long, float, double , decimaluint long, ulong, float, double , decimal

long float, double , decimal

char ushort, int, uint, long, ulong, float, double , decimal

float double

ulong float, double , decimalWhen one data type is converted explicitly to another data type, with the help or pre-defined functions. Example: //explicitly from floating-point to integer

float i=123.45f; int x=(int)i;

C# allows to convert explicitly from type to another type ie., listed below:

Table 2.6: Lists of Explicitly conversionFrom To

sbyte byte, ushort, uint, ulong, or charbyte sbyte, charshort sbyte,byte, ushort, uint, ulong, charushort sbyte, byte, short, charint sbyte, byte, short, ushort, uint, ulong, charuint sbyte, byte, short, ushort, uint, ulong, charlong sbyte, byte, short, ushort, uint, ulong, charulong sbyte, byte, short, ushort, uint, ulong, charchar sbyte, byte, or shortfloat sbyte, byte, short, ushort, int, uint, long, ulong, char, decimaldouble sbyte, byte, short, ushort, int, uint, long, ulong, char, float, decimaldecimal sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double

Prepared By Namratha K

Page 55: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

55

Chapter 2 Introducing C#

Example : using System;namespace Class_Demos{

class StringEx2{

public static void Main(){

double d = 55673.745;int i;i = (int)d;Console.WriteLine(i);Console.Read();

}}

}

2.7 Expression and Operators:

An expression is a set of language elements arranged together to perform a specific task or computation. To use expression, C# 2010 provides a complete set of language elements, such as variables, constants, operators, properties, and literals.

Operators play a vital role in performing some computation or other operations, such as variables, constants, operators, properties, and literals. The operators are listed in the below table.

Category

Primary

Table 2.7: List of operators

Operators DescriptionX .Y Accesses the member variables and methods of a class

f(x) Accesses methods and delegates of a class

a[x] Represents square brackets that are used with array, indexers, pointers, andattributes

x++ Increases the value of its operand (x) by 1

x-- Decreases the value of its operand (x) by 1

new Creates objects and call constructors

typeof Discovers information about reference and value types

checked Detects the overflow conditions in certain operations

unchecked Ignores the error caused by overflow conditions and accepts the generated resultregardless of the overflow conditions

-> Combines pointer dereferencing and member access. Pointer dereferencing is a

Prepared By Namratha K

Page 56: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

56

Prepared By Namratha K

Page 57: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

57

Chapter 2 Introducing C#

Category Operators Description

Binary

+ Gets the logical complement of the negative value- Gets the negation of the operand value.! Inverts the result of a Boolean expression.~ Inverts the binary representation of an expression.

++x Increases the value of its operand(x) by 1. It first increases the value of xby 1 and then assigns the increased value to it.

--x Decreases the value of its operand(x) by 1. It first decreases the value of xby 1 and then assigns the decreased value to it.

Category Operators Description Example

== Checks if the values of two operands are equal or not, if yes then (A == B) iscondition becomes true. not true.

Relational != Checks if the values of two operands are equal or not, if values are not (A != B) is

operand, if yes then condition becomes true. true.equal then condition becomes true. true.

> Checks if the value of left operand is greater than the value of right (A > B) is not

r Operato

<Checks if the value of left operand is less than the value of right (A >= B) isChecks if the value of left operand is greater than or equal to the value

operand, if yes then condition becomes true. (A < B) is true.

>= of right operand, if yes then condition becomes true. not true.

<= Checks if the value of left operand is less than or equal to the value of (A <= B) isright operand, if yes then condition becomes true. true.

&& Called Logical AND operator. If both the operands are non zero then (A && B) iscondition becomes true. false.

|| Called Logical OR Operator. If any of the two operands is non zero (A || B) is true.then condition becomes true.! operand. If a condition is true then Logical NOT operator will make

Called Logical NOT Operator. Use to reverses the logical state of its !(A && B) is

false.true.

Operat & which is 0000

Binary AND Operator copies a bit to the result if it exists in both (A & B) = 12,

operands.1100

Prepared By Namratha K

Page 58: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

58

Binary XOR Operator copies the bit if it is set in one operand but not (A ^ B) = 49,^ which is 0011both.

0001

Prepared By Namratha K

Page 59: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

59

Chapter 2 Introducing C#

CategoryOperator

s Description Example= Simple Exercise operator, Assigns values C = A + B assigns value of A + B

from right side operands to left side operand into CAdd AND Exercise operator, It adds right

+= operand to the left operand and assign the result C += A is equivalent to C = C + Ato left operandSubtract AND Exerciseoperator, It subtracts

-= right operand from the left operand and assign C -= A is equivalent to C = C - Athe result to left operandMultiply AND Exercise operator, It

*= multiplies right operand with the left operand C *= A is equivalent to C = C * Aand assign the result to left operandment

Assign Divide AND Exerciseoperator, It divides left/=

result to left operand

C /= A is equivalent to C = C / Aoperand with the right operand and assign the

Modulus AND Exercise operator, It takes C %= A is equivalent to C = C %%= modulus using two operands and assign the

eratOp

Aor result to left operand

<<= Left shift AND Exerciseoperator C <<= 2 is same as C = C << 2

>>= Right shift AND Exerciseoperator C >>= 2 is same as C = C >> 2

&= Bitwise AND Exerciseoperator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and Exerciseoperator C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and Exerciseoperator C |= 2 is same as C = C | 2

is Determines whether an object is of a certain If( Ford is Car) // checks if Ford istype. an object of the Car class.O

thersObject obj = newStringReader("Hello");

as Cast without raising an exception if the cast fails StringReader r = obj asStringReader;

2.7.1 Operator Precedence

The operators are associated with either the expression on its left or right, which is known as the associativity of the operator.

Prepared By Namratha K

Page 60: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

60

Prepared By Namratha K

Page 61: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

61

Chapter 2 Introducing C#

Table 2.8: Lists of Operator and their precedence

Operator Associativity

(x), (x.y), f(x), a[x], x++, x--,new, typeof, sizeof, checked, unchecked Left

+(unary), -(unary), ~, ++x, --x, (T)x Left

*, /, % Left

+, - [arithmetic] Left

<<, >> Left

<, >, <=, >=, is, as Left

==, != Left

& Left

^ Left

| Left

Prepared By Namratha K

Page 62: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

62

&& Left

|| Left

?: Right

=, *=, /=, %=, +=, -=, <<=, >>=, &=,^=, |= Right

2.7.2 Using the ?? (Null Coalescing) Operator:

The null coalescing (??) is mostly used with the nullable value type and reference type. The ?? operator is used between two operands where the first operand must be a nullable type. The second operand must be of the same type as the first operand or of the type that can be implicitly converted to the first type.

Syntax: < data_type > ? < variable_name > = null;Nullable_type ?? Value or Nullable type

It checks whether the value of the first operand is null or not.

If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand.

Example 13: In this example, we have declared i & j. This means that i and j variables contain either the integer value or the null value. We have assigned null value to the i variable and a value of 30 to the j variable. Using the ?? operator in the k = i ?? 25 statement, the compiler checks whether the value of i is null or not. As the value of

Chapter 2 Introducing C#

i is null, the value of right operand is returned. Similarly in the k = j ?? 25 statement, the value of j is 30, which is not null. Therefore, the value of j is assigned to the k variable

using System;

namespace Class_Demos

Prepared By Namratha K

Page 63: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

63

{class NullEX{

public static void Main() {

int? i = null; int? j = 30; int k;

k = i ?? 25; //check for null, here i is null, return right operand valueConsole.WriteLine("The Value of i is:" +i);

Console.WriteLine("The Value of k is:" +k);*/ k = j ?? 25; //check for null, here j is not null, //return left operand value

Console.WriteLine("The Value of j is:" +j);Console.WriteLine("The Value of k is:" +k);

Console.Read();

} }}

2.7.3 Using the :: (Scope Resolution) OperatorThe scope resolution (::) operator is added between two identifiers to define their scope. The Left-hand identifier of the :: operator is taken as a global identifier, an extern, or alias. When the left-hand identifier of the :: operator is global, the global namespace is searched for right-hand identifier.

Syntax: global::global namespace

Example : using System;namespace Class_Demos{

class ScopeEx{

public class System {public void Print(){

global::System.Console.WriteLine("This is anexample of :: operator");

}}

Prepared By Namratha K

Page 64: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

64

Chapter 2 Introducing C#

//Define a constant "console" const string str = "Hello"; const string str1 = "World"; static void Main() {

System sys = new System(); sys.Print(); global::System.Console.WriteLine("Hi"); global::System.Console.WriteLine(str);

global::System.Console.WriteLine(str1);global::System.Console.Read();

}}

}

In the above example, we have used the :: operator with global identifier to access the identifiers globally in the application.

2.7.4 Using the is and as Operators:

The is operator checks whether an object is compatible with the given type or not and returns a Boolean result ie., either true or false. The object may either be of the same type or may be derived from that particular given type.

The as operator converts the reference types explicitly into a specific type. If the reference type is compatible with the specified type, it performs successful conversion; Otherwise, it returns the null value.Note that the as operator does not throw an exception.Example 15:

using System; namespace Class_Demos{

class IsAsEx {static void Main()

{ //using is operator object i = 25;object str = "C# 2010"; if (str is string)

Console.WriteLine("i is a string type");else

Console.WriteLine("i is an integer type");//using as operatorstring str1 = i as string;

Prepared By Namratha K

//cannot be cast i to string

Page 65: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

65

string str2 = str as string; //casting str to string Console.WriteLine("The value of str1 is" + str1); Console.WriteLine("The value of str2 is" + str2); Console.ReadKey();

}}}

Prepared By Namratha K

Page 66: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

66

Chapter 2 Introducing C#

2.8 Boxing and Unboxing:Given that .NET defines two major categories of types are:

i. Boxing is the conversion of a value type to a reference type. ii. Unboxing is the converting a reference type to a value type.

Converting from value type to reference type: BoxingConverting a value type to reference type is called Boxing. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap.Example: int foo = 42; // Value type.

object bar = foo; // foo is boxed to bar.

In the first line of this code, we’re creating a variable (foo) of type int. As you know, int is a value type because it’s a primitive type. In the second line, the compiler sees the variable foo being copied to a reference typeimplicitly, which is represented by the variable bar. Boxing is a mechanism in which value type is converted into reference type. It is implicit conversion process in which object type (super type) is used. In

this process type and value both are stored in object type

Converting from reference type to value type: UnboxingUnboxing is the opposite operation to boxing. An unboxing conversion permits an explicit conversion from reference type to any value-type. An unboxing operation consists of

i. Checking the object instance to make sure it is a boxed value of the given value type ii. Copying the value from the instance into the value-type variable

Example: int foo = 42; // Value type.object bar = foo; // foo is boxed to bar.int baz = (int)bar; // Unboxed back to int.

When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.Example 16:

using System; namespace Examples {

class BoxUnboxDemo{static void Main(string[] args){

int i = 10;object o = i; // boxingint j = (int)o; // unboxingConsole.WriteLine("value of o object(boxing): " +o); Console.WriteLine("Value of j(unboxing): " +j); Console.ReadLine();

}}}Prepared By Namratha K

Page 67: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

67

Chapter 2 Introducing C#

2.9 Control Flow statements [Selection Statements, Iteration Statements and Jump Statements]:C# provides 2 Decision Statements as follows below:

if/else statement[simple if, if/else, else if ladder, Nested if]

switch statement

C# provides 4 Iteration Constructs as follows below:

for loop while loop foreach/in loop do/while loop

C# provides 4 types of statements that control the flow of control in a program:

break continue goto return

2.9.1 Decision Statements:i. if Statements:

‘If-else’ statements are used to run blocks of code conditionally upon a boolean expression evaluating to true. The‘else’ clause, present in the following example, is optional.Different types of if statements are...

simple if if-else statements

Nested if statements

Ladder if-else statements (if-else-if....)

Syntax: if (expression) statement1 ; else statement2;

Example:if(a==10) Console.WriteLine(“A is equal to 10”);else Console.WriteLine(“A is not equal to 10”);

Unlike in C and C++, however, the if/else statement in C# operates only on Boolean expressions, not values such as 1, 0 and if statement may be composed of complex expressions as well and can contain else statements to perform more-complex testing.

Prepared By Namratha K

Page 68: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

68

Chapter 2 Introducing C#

ii. switch statements:

The switch statements help to control complex conditional and branching operations. The switch statement transfers control to a statement within its body.

Syntax:Switch(expression){ case (constantExpression): //Staements break;

case (constantExpression): //Statements break; default: // statement;}

Example :

switch (country){

case "England":language = "English"; break;

case "Germany":case "Switzerland": language = "German"; break;case null:

Console.WriteLine("no country specified"); break;default:

Console.WriteLine("don't know the language of" + country);break;

}

First, the switch_expression is evaluated, and then the result is compared to each of the constant-expressions or case labels, defined in the different case statements. Once a match is made, control is passed to the first line of code in that case statement.

In order to come out of a particular case, we have to use break statement and program will comes out of the switch body. Without break, the program continues to the next case, executing the statements until a break or the end of the statement is reached. In some situations, this continuation may be desirable.

The default statement is executed if no case constant-expression is equal to the value of switch (expression). There can be at most one default statement. The default statement need not come at the end; it can appear anywhere in the body of the switch statement. A case or default label can only appear inside a switch statement.

The type of switch expression and case constant-expression must be integral. The value of each case constant-expression must be unique within the statement body. Switch statements can be nested.

Prepared By Namratha K

Page 69: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

69

Chapter 2 Introducing C#

2.9.3 Iteration Constructs:

In C#, the while, do/while, for, and foreach statements enable you to perform controlled iteration, or looping. In each Chapter 2 Introducing C#

case, a specified simple or compound statement is executed until a Boolean expression resolves to true, except for the case of the foreach statement, which is used to iterate through a list of objects.

The while Statements:

A ‘while’ loop executes a statement, or a block of statements wrapped in curly braces, repeatedly until the condition specified by the boolean expression returns false. This statement is also called as entry-controlled loop.Syntax: while( Boolean-expression) { Statements; }

Example:int a=1;while(a<4){ Console.WriteLine(a); a++; a++;}

The do/while Statements:

A ‘do -while’ loop is just like a ’while’ loop except that the condition is evaluated after the block of code specified in the ‘do’ clause has been run. So even where the condition is initially false, the block runs once. This statementis also called as exit- controlled loop

Syntax: Example :do int a=4;{ do

{Statements; Console.WriteLine(a);}while (Boolean-expression); }while(a<3);

The for Statement:

Prepared By Namratha K

Page 70: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

70

The statements in the for loop repeat continuously for a specific number of times. The while and do-while loops repeat until a certain condition is met. The for loop repeats until a specific count is met. Use a for loop when the Chapter 2 Introducing C#

number of repetition is know, or can be supplied by the user.

Syntax:for (initialization; Boolean-expression; increment/decrement){

Statements;}

Note that any of the three parts — initialization, Boolean-expression, increment/decrement—can be empty.

The initialization is evaluated before the loop begins. It is acceptable to declare and assign in the initialization (such as int x = 1 ;). This initialization is evaluated only once at the beginning of the loop.

The Boolean-expression will evaluate to true or false. While TRUE, the body of the loop repeats. When the

Chapter 2 Introducing C#

Boolean-expression becomes FALSE, the looping stops and the program continues with the statement immediately following the for loop body in the program code.

The increment/decrement executes after each trip through the loop. The count may increase /decrease by 1 or of some other value.

Example :for (int i = 0; i < n; i++)

sum += i;

The foreach Statement:

The ‘foreach’ loop is used to iterate through the values contained in a collection. When a ‘foreach’ loop runs, the given variable1 is set in turn to each value exposed by the object named by variable2.

int[ ] a=1,2,3;Syntax: foreach (type variable1 in variable2) Example :{ foreach(int b in a)

{Statements;Console.WriteLine(b);}

}

The main drawback of ‘foreach’ loops is that each value extracted (held in the given example by the variable ‘b’) is read-only.

2.9.4 Jump Statements or Flow Control Constructs:

Inside the embedded statements of any iteration statement, you can control the flow of execution with one of several

Prepared By Namratha K

Page 71: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

71

statements collectively known as jump statements: break, continue, goto, and return.

Chapter 2 Introducing C#

The break Statements:

You use the break statement to terminate the current enclosing loop or conditional statement in which it appears. Control is then passed to the line of code following the embedded statement of that loop or conditional statement. The break statement, which has the simplest syntax of any statement, has no parentheses or arguments.

Syntax:break;

Example :int i=0;

Output:while(true)0{ 1

Console.WriteLine(i); 2if(i==5) 3

break; 4i++;

}

The continue Statements:

The continue statement enables you to alter the execution of a loop. However, instead of ending the current loop’s embedded statement, the continue statement stops the current iteration and returns control to the top of the loop for the next iteration.

Syntax: continue;

Example 23:

int y=0;for(int x=1;x<101;x++){

if((x%7)==0)continue;

y++;}

The above example uses the ‘continue’ statement to count the number of values between 1 and 100 inclusive that are not multiples of seven. At the end of the loop the variable y holds the required value.

Prepared By Namratha K

Page 72: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

72

Chapter 2 Introducing C#

Assignment

1. Explain different types of formal parameters in C# with example.

2. Explain the following operators with simple examples :

i ) ?? (null coalescing)

ii) : : (scope resolution)

iii) is

iv) as 3. List and explain C# preprocessor directives.

4. Explain the following with example

i) Value types and reference types

ii) Boxing and unboxing.

5. Explain looping statements in C# with examples.

6. In detail discuss the control flow statements in C#

7. With an example illustrate type conversions.

8. Write short notes on Identifiers and keywords

Prepared By Namratha K

Page 73: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

namespace XYZ{

class class_name{

- - - - - -}

73

Chapter 3 Namespaces, Classes, Objects and Structs

Namespaces, Classes, Objects and Structs

3.1 Introduction:

The C# programming language offers a rich set of functionalities and powerful constructs that allow you to quickly and easily create new applications with minimum code.

The most basic aspect of programming involves the use of following: Namespaces: Allow to group different entities such as classes, objects, and functions under a common

name. Classes: Represents data structure that may contain data members, such as constants and fields, function

members, such as methods, properties, events and nested types. Objects: Represents a building block that helps you to access the members of a class, such as

fields, methods and properties Structs: Represents data structures that can contain data members and function members.

3.2 Namespaces:A namespaces is wrapper that is wrapped around one or more structural elements to make them unique and differentiated from other elements.

To declare namespace in C# .Net has a reserved keyword “namespace”. If a new project is created in Visual Studio .NET it automatically adds some global namespaces. These namespaces can be different in different projects. But each of them should be placed under the base namespace “System”. In C# all namespaces should import by using keyword, which can tell the compiler which namespaces and libraries of the code you want to use in the system.

Syntax:

Example :using System; namespace Program{

public Class MyApp {public static void Main() { Console.WriteLine("Hello World");

Prepared By Namratha K

Page 74: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

74

}}}

Chapter 3 Namespaces, Classes, Objects and Structs

3.3 The System namespace:Within System we can find numerous useful types dealing with built in data, mathematical computations, random number generation, environment variables, and garbage collection, as well as a number of commonly used exceptions and attributes. So System is a root namespace.

The following are some of the common namespaces provided by the .NET Framework class library:

Table 3.1: Lists of common pre-defined namespaces in .NET Framework

Namespaces Meaning

System.Collections System.Collections.Generic

These namespaces define a number of stock container objects (ArrayList, Queue, and so forth), as well as base types and interfaces that allow you to build customized collections. As of .NET 2.0, the collection types have been extended with generic capabilities

System.Data System.Data.Odbc System.Data.OracleClient System.Data.OleDb System.Data.SqlClient

These namespaces are used for interacting with databases using ADO.NET.

System.Diagnostics Here, you find numerous types that can be used to programmatically debug and trace your source code.

System.Drawing System.Drawing.Drawing2D System.Drawing.Printing

Here, you find numerous types wrapping graphical primitives such as bitmaps, fonts, and icons, as well as printing capabilities.

System.IO System.IO.Compression System.IO.Ports

Include file I/O, buffering, and so forth. As of .NET 2.0, the IO namespaces now include support compression and port manipulation.

System.Net Contains types related to network programming (requests/responses, sockets, end points, and so on).

System.Reflection System.Reflection.Emit

Define types that support runtime type discovery as well as dynamic creation of types.

System.Runtime.InteropServices Provides facilities to allow .NET types to interact with “unmanaged code” (e.g., C-based DLLs and COM servers) and vice versa.

System.Runtime.Remoting Defines types used to build solutions that incorporate the .NET remoting layer.

System.SecuritySecurity is an integrated aspect of the .NET universe. In the security-centric namespaces you find numerous types dealing with permissions, cryptography, and so on.

Prepared By Namratha K

Page 75: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

75

System.Threading This namespace defines types used to build multithreaded applications.System.Web System.Web.Security

A number of namespaces are specifically geared toward the development of.NET web applications, including ASP.NET and XML web services.

System.Windows.Forms Contains types that facilitate the construction of traditional desktop GUI applications.

System.Xml The XML-centric namespaces contain numerous types used to interact with XML data.

System.Linq Includes classes that allow you to use Language Integrated Queries in your application

3.4 Classes and Objects:

Classes allows you to control all the functions that can be applied to a given set of data as well as how to access the data. Classes also give you the ability to extend a runtime environment and allow the developer to reuse the existing functionalities of the runtime environment. Then use that class to create the objects as needed.In this section, you learn to perform the following tasks:

Creating a class Using Nested Classes Creating an object Using methods as Class Members Using this Keyword Passing an object as an argument to a method Creating an Array of Objects Returning a value from a method Defining partial classes and methods Describing access modifiers

3.4.1 Creating a class:A class declaration in C# is composed of attributes, modifiers, the class name, base class and interfaces, and a body. Attributes, modifiers, and bases are all optional.Syntax:

The body of the class contains class members that can include constants, fields (or variables), methods, properties, indexers, events, operators, and nested types. Nested types are defined by class, interface,

Prepared By Namratha K

class

<Class_name> {

<access_modifier> [static] variable_type fields, constants // for object-oriented programming<access_modifier> [static] return_type methodName(args..){ - - - - - - - }... constructors, destructors ...... properties ...// for component-based programming... events ...... indexers ... // for convenience... overloaded operators ...

Page 76: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

using System;

class HelloClass {

public static int Main(string[] args){ Console.WriteLine("Hello World!"); Console.ReadLine();

return 0;

76

delegate, struct, or enum declarations within the class body.

Chapter 3 Namespaces, Classes, Objects and Structs

C# program can be written as follows below: Example :

It is declared inside a class. It must be static and it should not be public.

C# executable program must include the Main() method in any one of the classes.

public: is an access modifier that tells the main method is accessible by anyone.

static: the Main method is a global one and can be called without creating an instance of the class.

void: is a type modifier, that the Main method does not return any value.

string[] args: method has single parameter which happens to be an array of strings and also contain any

number of incoming command – line – arguments.

Rules to use members: All the keywords are in the

lowercase ex: public, global, private and so on.

All the namespaces, types and member names begin with an initial capital letter and have capitalized by embedded wordsex: Console, WriteLine, MessageBox, System

3.4.2 Creating an object:

In C#, objects help you to access the members of a class – fields, methods and properties by using the dot () operator.

An object is a given instance of a particular class in memory. In C#, the new keyword is the way to create an object.

Syntax: <ClassName> <ObjectName> = new <ClassName>();

Prepared By Namratha K

Page 77: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

77

Chapter 3 Namespaces, Classes, Objects and Structs

3.4.3 Using “this” Keyword:

The “this” keyword refers to the current instance of a class. With the “this” keyword, you can access an instance of a class and use it with instance methods, instance constructors, and instance properties.

Syntax: this.members;

Note: To access the instance members of a class, use dot() operator Cannot be used with static members because static members are accessed by a class and not by

the instance of the class.Example 3:using System; namespace Class_Demos{

class Student{ string name, sid; int marks;//public Student() { }public Student(string name, string sid, int marks){

this.name = name; this.sid = sid; this.marks = marks;

}//If the user calls this ctor, forward to the 3-arg version.//public Student() : this("abc","MCA01",95) { } public Student(){

name = "abc"; sid = "MCA01";marks = 95;

}public void displayData(){

Console.WriteLine("Name: {0}\nID: {1}\nMarks:{2}", name,sid, marks);

}}class thisdemo {

static void Main(string[] args){

Prepared By Namratha K

Page 78: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

78

Student st1 = new Student(); Console.WriteLine("Student Details:"); st1.displayData();Student st2 = new Student("def", "MCA02", 85);

Chapter 3 Namespaces, Classes, Objects and Structs

st2.displayData();Console.ReadLine();

}}

3.4.4 Create an Array of Objects:

To create an array of objects in C#, follow the below steps: Create an array Then create the individual elements of the array.

Syntax: <class_type>[] object_name = new <class_type>[size];Example: Employee[] manager = new Employee[size];

Note that you cannot create an array and its individual elements simultaneously.

3.4.5 Using the Nested Classes:

A Nested class is a class that is defined inside another class. This class acts as the member of the parent class in which it is defined.

Advantage: Accessing all the members of its outer class.

Example :

using System;namespace Class_Demos {

class OuterClass

{int i;public OuterClass() { i = 10; } public void OutDisplay() {

Console.WriteLine("This is Outer Class");}public class InnerClass {

public void InDisplay(OuterClass o)

Prepared By Namratha K

Page 79: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

79

{Console.WriteLine("This is Inner Class"); Console.WriteLine("i value is:" +o.i);

}}}class NestedClEx{

public static void Main(){Chapter 3 Namespaces, Classes, Objects and Structs

//Creating instance to outer class OuterClass ob1 = new OuterClass(); ob1.OutDisplay();//Creating instance to inner classOuterClass.InnerClass iob = new OuterClass.InnerClass(); iob.InDisplay(ob1);

Console.Read();

}}}

3.5 Defining Partial Classes and Method:The partial class is a class that enables you to specify the definition of a class, structure, or interface in two or more source files. All the source files, each containing a section of class definition, combine when the application is complete. You may need a partial class when developers are working on large projects.A partial class distributes a class over multiple separate files; allowing developers to work on the class simultaneously. You can declare a class as partial by using the “partial” keyword. All the divided sections of the partial class must be available to form the final class when you compile the program. Let’s see that in below figure:

Prepared By Namratha K

Program1.cs

Page 80: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

80

All the section must have the same accessibility modifiers, such as public or private. Syntax:

Chapter 3 Namespaces, Classes, Objects and Structs

public partial class student{ public void avgmarks() { }

}public partial class student{

public void avgmarks() { }}

Example :using System;namespace Class_Demos{

partial class MyTest

{private int a; private int b;public void getAnswer(int a1, int b1){

a = a1; b = b1;

}}

partial class MyTest

{public void DisplayAns(){

Prepared By Namratha K

Program2.cs Compile to one single class

Page 81: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

81

Console.WriteLine("Integer values: {0}, {1}", a, b); Console.WriteLine("Addition:{0}", a + b); Console.WriteLine("Multiply:{0}", a * b);

}}

class PartialEx{

public static void Main(){

MyTest ts = new MyTest(); ts.getAnswer(2, 3); ts.DisplayAns(); Console.Read();

}}}

Chapter 3 Namespaces, Classes, Objects and Structs

Partial method are only allowed in partial types, such as classes and structs. A partial method consists of 2 parts that listed below:

Deals with defining the partial method Deals with implementing the partial method declaration

Rules: Must have a void return type No access modifier are allowed for declaring a partial method except for static

Partial methods are private by default.

3.5.1 Using methods as Class Members

Members of a class are the elements that are declared in the class. The following code snippet shows the syntax to declare the members of a class (methods and variables).

Example: class square{ int side;public int area(){

return(side*side);}

}

Prepared By Namratha K

Page 82: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

82

Constructors and destructors are special methods that are present in every class. The constructor method initializes all the class members whenever you access the class The destructor method destroys them when the objects are not required anymore. Each class has its own Constructor and Destructor and they are called automatically when the instance of

a class is created or destroyed.

3.5.2 Method Parameter Modifiers:

There are four different kinds of formal parameters in C#:Table 3.2: List of parameter modifiers

Modifiers Meaning(none)Value parameter

parameter is not marked with a parameter modifier, it is assumed to be passed by value, meaning the called method receives a copy of the original data.

OutOutput parameter

parameter is attached with an out modifier, then we can return a value to a calling method without using a return statement. If the called method fails to assign output parameters, you are issued a compiler error.

paramsParameters

This parameter modifier allows you to send in a variable number of identically typed arguments as a single logical parameter. A method can have only a single params modifier, and it must be the final parameter of the method.

RefReference

The value is initially assigned by the caller, and may be optionally reassigned by the called method. No compiler error is generated if the called method fails to assign a ref parameter.

Note: These modifiers can use for both value type and reference type.

i. Value parameter:By default, the parameters are passed to a method by value. So, the changes made for parameters within a method will not affect the actual parameters of the calling method. Look at the following program which tries to swap the number but does not succeed just because call-by-value does not affect the actual parameter.

using System; namespace Examples {class ValModifier {

static void swap(int x, int y){ int temp = x;x = y; y = temp;

}static void Main(){

int x = 10, y = 12;Console.WriteLine("Before: x={0}, y={1}", x, y); swap(x, y);Console.WriteLine("After: x={0}, y={1}", x, y);

Prepared By Namratha K

Page 83: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

83

Console.ReadKey();} } }

In the above example, the value of x and y are not changed in main method even when we call the function swap(). This is because, a new memory is created for the parameter when the function is called and all the changes will occur in that new memory location and that change is not reflected in the main method. So the output of above program will be x=10 and y= 12 but not x=12 and y=10.

ii. ref Parameter:Now consider the use of the C# ref parameter modifier. Reference parameters are necessary when you wish to allow a method to the same storage location is used, so the value of the variable in the function member and the value of the reference parameter will always be the same.

Let’s check out the use of the ref keyword by way of a method that swaps two strings: Example 8: using System; namespace Examples

Chapter 3 Namespaces, Classes, Objects and Structs

{class RefModifier {

public static void swap(ref int x, ref int y){

int temp = x; x = y;y = temp;}

static void Main(){int x = 10, y = 12;Console.WriteLine("Before: x={0}, y={1}", x, y); swap(ref x, ref y);Console.WriteLine("After: x={0}, y={1}", x, y); Console.ReadKey();

}}}

Here, the value of x and y are changed in main method when we call the function swap(). This is because, Rather than creating a new storage location for the variable in the function member declaration, the same storage location is used, so the value of the variable in the function member and the value of the reference parameter will always be the same so that change is reflected in the main method. So the output of above program will be x=12 and y= 10.

iii. out Parameter:In some of the methods, we need to return a value to a calling method. Instead of using a return statement, for this C# provides a modifier for a parameter as out. The usage of out can be better understood by the following program.

Prepared By Namratha K

Page 84: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

84

Example :

Chapter 3 Namespaces, Classes, Objects and Structs

Output parameters are very similar to reference parameters. The only differences are. The parameter is considered initially unassigned The parameter must be assigned a value before the function member completes normally.

The out parameter is certainly useful when we need more values to be returned from a method. Consider one more program.

Example 10:using System;

namespace Examples{

class OutModifier1 {static void CallFun(out int x, out string s){

x = 10;s = "Ten";

}static void Main() { int x;

string str;CallFun(out x, out str); Console.WriteLine("x={0}, str={1}", x, str); Console.ReadKey();

Prepared By Namratha K

}}

}

add(x, y, out z); Console.WriteLine("z={0}", z); Console.ReadKey();

y;

Main()

add(int x, int y, out int z)

static void

{

z = x +

}

static void

using

System;

Page 85: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

85

}}

}

iv. params Modifier:The params keyword of C# allows us to send multiple arguments as a single parameter. The usage of params can be better understood by the following program.

Example 11:using System;

namespace Examples {class ParamModifier {

static void display(params int[] arr){ for(int i=0;i<arr.Length;i++)

Console.WriteLine("a[{0}] is: {1} ",i,arr[i]);}static void Main() { int[]

Chapter 3 Namespaces, Classes, Objects and Structs

a={10,20,30,40};display(a); Console.ReadKey();

}}

In the above program we can observe that for the params parameter, we can pass an array or set of individual elements. We can use params even when the parameters to be passed are of different types; look at below the program.Example :

Prepared By Namratha K

Page 86: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

86

n the above program we can observe that for the params parameter, we can pass an array of different data types or set of different types of individual elements.

3.5.3 Difference between (out) and reference (ref) parameters:

The following are the differences:Chapter 3 Namespaces, Classes, Objects and Structs

i. The output (out) parameters do not need to be initialized before use in a called method. Because it is assumed that the called method will provide the value for such a parameter.Example:

The reference (ref) parameters must be initialized before sending to called method. Because we are passing a reference to an existing type and if we don't assign an initial value, it would be equivalent to working on a NULL pointer.

Example:Prepared By Namratha K

}}

}

}

static void Main()

{

int x = 10;

string s = "Good Morning"; bool b = true;

a boolean.", arr[i]);

is

a string.", arr[i]);

an integer.", arr[i]);

Console.WriteLine("{0} is if (arr[i] is string)

Console.WriteLine("{0} is if (arr[i] is bool)

using

System;

namespace Examples{ class ParamModifier1 {

static void display(params object[] arr)

int x = 10, y = 12, z; add(x, y, out z);

int x = 10, y=2 ; swap(ref x, ref y);

Page 87: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

87

ii. In the out parameter, compiler error is generated if the called method fails to assign out parameter. Example:

In the ref parameter, no compiler error is generated if the called method fails to assign a ref parameter. Example:

3.5.4 Passing an object as an argument to a method:The this keyword refers to the current instance of a class. You can also use it to pass an object to a method belonging to another class.using System; namespace Class_Demos{

class Employee{string name; double salary;

Prepared By Namratha K

static void swap(ref int x,ref int y)

{

int temp;temp=x; x = y;y = temp;//instead of x and y we can use a and b. no errors occurred.

Page 88: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

88

Chapter 3 Namespaces, Classes, Objects and Structs

public void ReadData(){

Console.WriteLine("Enter Name"); name = Console.ReadLine(); Console.WriteLine("Enter Salary");salary = double.Parse(Console.ReadLine());

}public void ShowData(){

Console.WriteLine("Employee Datails"); Console.WriteLine("Name " + name); Console.WriteLine("Tax is " + Tax.calcTax(this)); Console.Read();

}

class Tax{

public static double calcTax(Employee e){

return (0.08 * e.salary);}

}}

class PassObject{

static void Main(){

Employee emp = new Employee(); emp.ReadData(); emp.ShowData(); Console.ReadKey();

}}

In the above example, an object of the Empoyee class is passed as an argument to the CalcTax() method of the Tax class with the help of the this keyword.

3.5.5 Returning a Value from a Method:A method can return a value to the caller of the method. If the return type is void, then the method will not return any value. If the return type is other than void, such as int, double, string or class_type then the method can return any type of value using return keyword.

Prepared By Namratha K

Page 89: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

89

Chapter 3 Namespaces, Classes, Objects and Structs

Example :using System; namespace Class_Demos{

class MyArea {double l, b, area; public double RectArea(){

Console.WriteLine("Enter the Length"); l = double.Parse(Console.ReadLine());

Console.WriteLine("Enter the Breadth"); b = double.Parse(Console.ReadLine()); area = l * b;Console.WriteLine("The area of Rectangle is:" + area); return (area);

}}class ReturnValue{

static void Main(){

MyArea obj = new MyArea(); obj.RectArea();Console.WriteLine("Press Enter to quit...."); Console.ReadLine();

}}}3.6 Describing Access Modifiers:Access modifiers help to avoid jumbling of data and methods with the existing code as well as protect an object of a class from outside interference. These modifiers do this by defining a certain scope to access data and methods in a restricted manner.

Table 3.3: List of the access modifiers

Modifiers Meaningpublic Allows public access to members both inside and outside a class without any restrictions.

internal Allows internal access to members. Only the current assembly can access these members.

protectedAllows protected access to members. You can access protected members from either the class in which they are declared or a class derived from the class in which they are declared.

privateAllows private access to members. Private members have the least access permission level; you can either access then within the body of the class or in the structure in which they are declared.

protected internal Allows access to the members of the current assembly, the containing class, and the class derived from the containing class.

Prepared By Namratha K

Page 90: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

90

Chapter 3 Namespaces, Classes, Objects and Structs

3.7 Constructors and Destructors:A constructor is called when an object is first created. A destructor (or finalizer) is called when the object is finally destroyed and the garbage collected. The constructor is called with the same name as the class; whereas, the name of the destructor is same name as the class name prefixed with a tilde(~). You can use a constructor to initialize objects and set any parameters. And also constructor can accept arguments.

Example: Rules:

Constructors will be having the same name as that of its containing class

Constructors do not return a value

Constructors can be overloaded except static constructors

Constructor can’t be get inherited

A class has atleast one constructor also known as default constructor.

Types of Constructors:

In C#, we are having the following different types of constructors:

Default Constructor: A constructor that takes no parameters is called a default constructor. Default constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new.

Parameterized Constructors: At a time, we will require initializing class members during instantiation and this is the time where parameterized constructor will come into picture.

Note: A default constructor should be explicitly declared while declaring parameterized

constructor. Example 15: using System;

namespace Examples{

public ConsDemo()// Default constructor.

Console.WriteLine("Default ctor called!");}

public ConsDemo(string msg) // Custom ctor

Console.WriteLine("Custom ctor called!");

userMessage = msg;

}

public static int Main(string[] args) {

Prepared By Namratha K

public class clsname

{

clsname()

{

//body

}

~clsname()

Page 91: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

91

Chapter 3 Namespaces, Classes, Objects and Structs

// Call default ctor. ConsDemo c1 = new ConsDemo();

Console.WriteLine("Value of userMessage:{0}",c1.userMessage);

}

}

You can see the program that the default constructor has assigned the string field to its default value (null), while the custom constructor has assigned the member data to the user-supplied value.

3.7.1 Creating a Copy Constructors:

A Copy constructor is used to create a copy of an existing object as new object. This constructor takes the reference of the object to be copied as an arguments. In C#, does not provide the copy constructor by default, so you need to write a separate method or copy a constructor.

Example 16:using System; namespace Class_Demos{

class CarClass { string modelname; double mileage;public CarClass(string modelname, double mileage){

this.modelname = modelname; this.mileage = mileage;

}

public CarClass(CarClass mycar){

modelname = mycar.modelname; mileage= mycar.mileage;

}public void details(){

Console.WriteLine("Car " + modelname); Console.WriteLine("Mileage" + mileage);

} }class CopyConst{

public static void Main(){

CarClass car1 = new CarClass("Zen", 16.5); car1.details();CarClass car2 = new CarClass(car1); car2.details();Console.WriteLine("Press Enter to QUIT. . . "); Console.Read();

}} }

Prepared By Namratha K

Page 92: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

92

Chapter 3 Namespaces, Classes, Objects and Structs

In the above example, we first create an object of the CarClass class, car1, by passing two arguments to the constructor of the CarClass class. Then, we create another object of the CarClass class, car2, by copying the data of the car1 object.

3.7.2 Calling a Destructor of a Class:

Destructor is a method that is called to destroy the objects that are no longer in use. A class can have only one destructor. A destructor is declared using the tilde(~) sign, followed by the name of the destructor.

Example : using System; namespace Class_Demos{

class Test {public Test() {

Console.WriteLine("Constructor called to initializethe object");

}~Test(){

Console.WriteLine("Destructor called to release the memory which is allocated");

Console.ReadKey();}

}class DestExam{

static void Main(){

Test tobj = new Test();//Console.ReadKey();

}}

}

A destructor ~Test() called automatically. This destructor destroys the tobj object of the Test class, when it is no longer in use.

3.7.3 Constant Data:In C# constant data can be specified in two ways, they are:

i. using “const” modifierii. using “readonly” modifier

Defining constant data:Constants are fields whose values are set at compile time and can never be changed. However, a constant differs from a standard variable because once defined, the value assigned to the constant can

Prepared By Namratha K

Page 93: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

93

Chapter 3 Namespaces, Classes, Objects and Structs

never be changed. A C# offers the const keyword to define variables with a fixed, unalterable value. A constant field is declared using syntax as shown below:

modifiers const data_type var_name = value;

Constants are declared with the const modifiers. Only the C# built-in types may be declared as const. C# does not support const methods, properties, or events. Constants can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the constant.

Example 18: using System; namespace Examples {

class ConstDemo {

const float PI = 3.146F; static void Main(){

Console.Write("Enter Radius:");float r=float.Parse(Console.ReadLine()); Console.WriteLine("Area of Circle: {0}", PI * r * r); Console.ReadKey();}}}

3.7.4 Defining readonly fields:

A readonly member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared. To define a read-only field, make use of the C# “readonly” keyword.

Unlike const however, read-only fields are not implicitly static; therefore if you wish to expose such data at class level, the static keyword must be included. Read-only fields have another distinction from constant data: their value may be assigned within the scope of a constructor. This can be very useful if the value to assign to a read- only field must be read from an external source.

Example :using System;

namespace Examples { class ROnlyDemo {

int A;readonly static ROnlyDemo ob1 = new ROnlyDemo(100);

ROnlyDemo() {Console.WriteLine("Default Constructor");

}

Prepared By Namratha K

Page 94: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

94

Chapter 3 Namespaces, Classes, Objects and Structs

ROnlyDemo(int n){ A = n;Console.WriteLine("A={0}", A);

}static void Main(){

ROnlyDemo ob2 = new ROnlyDemo(); Console.ReadLine();

}}}

Error occurs in different situation when variables declared as const and readonly: If you use the const keyword in the place of readonly, you will receive compiler error.

Example:

Output:

Generate compiler error because const keyword cannot be used to creating constant instance of class.

If you try to change the ob1 field within your program, you receive a compilation error. Example: using System;

namespace Examples{

class ROnlyDemo1 { int A;readonly static ROnlyDemo1 ob1 = new ROnlyDemo1(100);

ROnlyDemo1(){Console.WriteLine("Default Constructor");

}ROnlyDemo1(int n){ A = n;

Console.WriteLine("A={0}", A);}static void Main(){

ROnlyDemo1 t = new ROnlyDemo1(); t.ob1 = new ROnlyDemo1(200); Console.ReadLine();

}}

Prepared By Namratha K

class ROnlyDemo {int A;const ROnlyDemo ob1 = new ROnlyDemo(100);- - - - -

}

Page 95: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

95

Chapter 3 Namespaces, Classes, Objects and Structs

Output:

3.8 Static Classes and Static Class Members:C# class (and structure) members may be defined using the static keyword.

Static methodsStatic dataStatic

classes Conventions to use

“static” keyword :

can be used with classes, fields, methods, properties, operators, events, and constructors

static methods and properties can only access static fields and static events.

but cannot be used with indexers, destructors, or types other than classes.

can't use “this” keyword.

Note: static method is also known as class method[belongs to class not an object] non-static method is known as instance method.

Static methods

A C# class can contain both static and non-static methods. When we declare a method with the help of the keyword static, it becomes a static method.

For using static methods,

Creation of instance is not necessary. A static method only access other static data and methods

Static methods cannot access data members and members’ method directly – they must use an object reference.Static data members:

When we declare a static field inside a class, it can be initialized with a value or all un-initialized static fields automatically get initialized to their default values when the class is loaded at first time.

Characteristics: It is visible only within the class, but its lifetime is the entire program. Only one copy of static data member will exists for the entire class and is shared by all the

objects of that class.

Prepared By Namratha K

Page 96: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

96

Chapter 3 Namespaces, Classes, Objects and Structs

No matter how many objects of a class are created. All static variables are initialized to zero when the first object of its class is

created.

When you create Stdata objects( std1, std2), memory for the non-static data field is allocated for each instance. On the other hand, Static data is allocated once and shared among all object instances of the same type. So the output of the record is 2 in both the instance of the class.

Static class:

When a class has been defined as static, no need to create an object. A static class must contain only static members, except for constants (if this is not the case, you receive compiler errors).

Main benefit: We do not need to make any instance of this class; all members can be accessible with its own name.

Example 22: using System;

namespace Examples {static class StClass { static int

record = 0;

static void printrecord(){

Console.WriteLine("No of stud record: {0}", record);}static void Main(){

record = 2; printrecord(); Console.ReadLine();}}

In the above example, StClass class is static class so it includes only static members. We can access all the member of the static class directly; no need of instance of the class. So that members record and printrecord() is accessing directly.

3.9 Properties:

A property is a member that provides a flexible mechanism to read, write or compute the value of a private field. You can implement properties with the type-safe get and set methods.

Syntax: set { <mutator-

body> } get

{ <accessor-body

Prepared By Namratha K

Page 97: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

97

>}

Chapter 3 Namespaces, Classes, Objects and Structs

The important thing is the “value” keyword, sets the value of the some property field with the contents of value token.Example: set{

usn=value;

}

Note: Keep in mind about property

Although you don’t have to have both a getter and a setter, you must have one of the two.

A property defined with both a getter and a setter is called a read-write property. A property defined with only a getter or accessor is called a read-only property. A property defined with only a setter or mutator is called a write-only property.

Example : using System;

namespace Chapter4_Examples{ class Student{string name, branch, usn;

public string Studusn{

set{ usn = value; } get{return usn;}

}}class GetSetDemo1 { static void Main()

{Student st1 = new Student(); st1.Studusn ="1ST14MCA05";Console.WriteLine("USN: " + st1.Studusn); Console.ReadKey();

}}

}

In the above example, we see the usage of Encapsulation by using properties. The property is composed using a get block(accessor) and set block(Mutator). The get block returns the value of the some property field. The set block sets the value of the some property field with the contents of “value” token. In the C# “value” keyword represents the right hand side of the assignment. The underlying data type of the value token depends on which sort of data it represents so that “value” token is called as object.

3.9.1 Read-only Property:

A read-only property is a property that has a get accessor but does not have a set mutator. This means that you can retrieve the value of a variable using a read-only property but you cannot assign a value to the variable.

Prepared By Namratha K

Page 98: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

98

Chapter 3 Namespaces, Classes, Objects and Structs

Example :using System;

namespace Class_Demos{

class Student{

string studusn;

public Student(){

studusn="1ST13MCA01";}public string Studusn{

get {return studusn;}

}}

class ReadOnly{

static void Main(){

Student st1 = new Student(); Console.WriteLine("USN: " + st1.Studusn); Console.ReadKey();

}}}

In the above example, the property “Studusn” is having only get accessor but not set mutator. So we can call

Studusn as a “read-only

property”. Static

Property:

C# also supports “static” properties. The static members are accessed at the class level, not from an instance(object) of that class. Static properties are manipulated in the same manner as static methods, as seen here:

For example, assume that the Student type defines a point of static data to represent the name of the institution studying these students. You may define a static property as follows:

Prepared By Namratha K

Page 99: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

class Student{private string usn=”1ST14MCA01”; public string Studusn{

protected set{ usn = value; } get{return usn;}

}}

99

Chapter 3 Namespaces, Classes, Objects and Structs

Example :

using System;namespace Chapter3_Examples{class Student{

string name, branch, usn;static string instName;

public static string Institution { set { instName = value; }

get { return instName; }}

class GetSetStatic { static void Main(){Student.Institution = "SaIT"; Console.WriteLine("InstitutionName: "+Student.Institution ); Console.ReadKey();

}}}

3.9.2 Accessibility of accessors:

In C#, accessors are the get and set sections of a property. The accessibility of an accessor represents its ability to access the members of a property. The get and set accessors have the same accessibility level. This means that both these accessors are public because the property itself is public.

Example: class Student{private string usn=”1ST14MCA05”; public string Studusn{

set{ usn = value; } get{return usn;}}

}

In C# 1.1, you cannot change the accessibility level of the get and set accessors separately. However, in C# and higher version, you can specify the accessibility levels of these accessors in a property separately as shown below.

Example:

Prepared By Namratha K

Page 100: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

100

Chapter 3 Namespaces, Classes, Objects and Structs

In the above example, as the property named Studusn itself is public, the get accessor is also public because it is not explicitly marked with any accessor modifier. However, the set accessor is explicitly marked with the protected access modifier. Hence, you can used the get method throughout the program, whereas, you can use the set method only inside the same class or a sub-class of the source class. The approach is known as Asymmetric accessor accessibility.

3.9.3 Anonymous types:

Anonymous types create unnamed structure types that you can add to the collections and access those structure types using the var keyword.

ORAnonymous types are the class types that consists of one or more public read-only properties. No other kinds of class members, such as methods or events are allowed. You can use the new keyword with an object initializer to create an anonymous type.

Syntax:

Where,var is used to declare implicitly typed local variable means it tells the compiler to figure out the type of the variable at compilation time. A var variable must be initialized at the time of declaration.Example:

Example :using System; namespace Class_Demos{

class AnonyTypes{

static void Main(){

var product = new { Name = "Keyboard", price = 650 };Console.WriteLine("Product Details"); Console.WriteLine("Name: " + product.Name); Console.WriteLine("Price: " + product.price);Console.WriteLine("Press Enter to quit.... ");

Prepared By Namratha K

var object_name = new {field variables…};

a = new[] { 0, 1}; // a is compiled as int[]

anno =new {name=“abc”, age=16}; // anon is compiled as an anonymous type

//i is compiled as an inti=5;var

var

var

Page 101: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

<access-modifier> <Return_Type> this [argument_list] {

get { // return the value specified by index }

set { // set the value specified by index }

}

101

Console.ReadLine();}}

Chapter 3 Namespaces, Classes, Objects and Structs

In the above example, we are defining a new anonymous type and also creating an object of that type with the name product. The type that we have defined has two variables, Name and price.

3.10 Indexers:

Indexers allow you to use a class as an array and enable an object to access the members of a class using an

index notation.

Syntax:

Where, The access modifier can be private, public, protected or internal

Return type can be any valid C# data type, such as int, float, double, string….

The this keyword shows that the object is of the current class.

The argument list specifies the parameters of the indexer.

Must have at least one parameter; otherwise the compiler gives and error.

Allows you to have multiple parameters and each parameter can be a different type,

separated by commas.

Parameter types can be int, enum, or string.

All indexers in the same class should have different signatures.

The get and set portions accessors is the same as that of the indexer to which they

belong. Example :

using System;namespace Class_Demos{

class Student{

string[] usn = new string[3];public string this[int index]

{

Prepared By Namratha K

Page 102: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

102

set { usn[index] = value; }

Chapter 3 Namespaces, Classes, Objects and Structs

get {if (index < 0 || index >= usn.Length)

return null;else

return (usn[index]);}

}}class IndexerDemo{

public static void Main(){

Student slist = new Student(); slist[0] = "1ST14MCA01"; slist[1] = "1ST14MCA02"; slist[2] = "1ST14MCA03";for (int i = 0; i < 3; i++)

Console.WriteLine(slist[i]);Console.WriteLine("Press Enter to QUIT..."); Console.ReadKey();

}}

Indexers have the following additional features: Inheritance – Allows inheritance, which means a derived class can inherit a base class indexer. However, modifiers such as virtual and override are used at the property level, not at the accessor

level. Polymorphism – Allows polymorphism, which means the derived class can override a base class

indexer. Uniqueness – Provides a signature that uniquely identifies an indexer. Non – Static – Indexer cannot be static. If you declare, the compiler generates an error.

Example :using System; namespace Class_Demos{

class Student{string name,usn,branch;public Student(string n,string u,string

b) { name = n;usn = u; branch= b;

}public Student(){}//Define a string indexerpublic string this[string

index] { get{if (index == "name")

return name;if (index == "usn") return usn;

if (index == "branch")

Prepared By Namratha K

Page 103: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

103

return branch;return "Unknown";

Chapter 3 Namespaces, Classes, Objects and Structs

}set { if(index=="name")

name = value; if (index == "usn")usn = value;

if (index == "branch") branch = value;

}}}class

IndexerDemo1 { static void Main(){

Student std1 = new Student("abc", "1ST14MCA01", "MCA"); Console.WriteLine("Name: " + std1["name"]);Student std2 = new Student(); std2["name"] = "def"; std2["usn"] = "1ST14MCA02";std2["branch"] = "MCA"; Console.WriteLine("*****Student details*****"); Console.WriteLine("Name: " + std2["name"]); Console.WriteLine("USN: " + std2["usn"]); Console.WriteLine("Branch: " + std2["branch"]); Console.ReadLine();

} }}

Difference between Properties and Indexers:

Table 3.4: List of differences between property and indexers

Property Indexer

Allows identification by its name

Allows identification by its signature

Allows methods to be called as if they were public data members

Allows elements of an internal collection or an object to be accessed by using an array notation on the object itself.

Allows access through a simple name

Allows access through an index

Uses static or an instance member

Uses an instance member only

Provides no parameters to the get accessor of a property

Provides the same formal parameter list as the indexer

Contains the implicit value parameter

Contains the same formal parameter list as the indexer, in addition to the value parameter.

Prepared By Namratha K

Page 104: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

104

Chapter 3 Namespaces, Classes, Objects and Structs

Assignment:

1. Write a note on .NET namespaces in C#.2. Describe the different access specifiers in C#.3. Explain the following with example : i) Static constructor ii) System namespace4. What are properties in C#? Explain read only and static properties with examples.5. With an example explain indexers.6. What are anonymous types?\7. List out different members of System Object class8. Why system . Object is called master node? List and explain the major methods of System.Object9. Write a note on string manipulation in C#. Explain atleast five methods of System.String class with

example10. Explain with an example static keyword. When used with i) Variable ii) Method iii) Constructor11. Explain two different roles of this keyword with example.12. Explain with example, Read-only properties and Write-only properties.13. Define Partial Method, with program

Prepared By Namratha K

Page 105: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

105

Chapter 4 Object- Oriented Programming with C#

Object- Oriented Programming with C#

There are mainly two types of programming models followed while developing a software application as mention below:

Procedural Oriented Programming (POP)

Object Oriented Programming (OOP)

POP is based on the concept of breaking a problem into modules, solving each module separately, and later combining all the solved modules to solve the entire problem. A module can be method that consists of a block of code. In the POP model, you can call one method from another. This implies that these methods are dependent on each other, thereby, making the reusability of code difficult.

The model of OOP has been introduced to overcome the difficulty on reusability of code. OOP uses the concept of classes and objects to reuse the existing code. A class acts as a blueprint or template to create instances or objects. This blueprint or template describes the state and behavior for all the objects of the class.

C# is an Object oriented Programming language. So like all Object oriented languages, C# will also supports following Object Oriented Principles.

1. Encapsulation : How does this language hide an object’s internal implementation?2. Inheritance : How does this language promote code reuse?3. Polymorphism : How does this language let you treat related objects in a similar way?

You also learn about abstraction, interfaces, sealed classes, sealed methods and extension methods.

4.1 Encapsulation:Encapsulation is the procedure of covering up of data and functions into a single unit. An encapsulated object is often called an abstract data type. We need of Encapsulation for the following reasons:Prepared By Namratha K

Page 106: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

106

Encapsulation is one of the fundamental principles of object-oriented programming. Encapsulation is a process of hiding all the internal details of an object from the outside world. Encapsulation provides a way to protect data from accidental corruption.

Encapsulation gives you the ability to validate the values before the object user change or obtain the value.

Encapsulation makes implementation inaccessible to other parts of the program and protect from whatever actions might be taken outside the function or class.

4.1.1 Encapsulation using Accessors and Mutators:

Rather than defining the data in the form of public, we can declare those fields as private so that we achieved encapsulation. The Private data are manipulated using accessor(get: store the data to private members) and mutator(set: to interact with the variable) methods.

Syntax:set { <accessor-body> } get { <accessor-body >}

Chapter 4 Object- Oriented Programming with C#

Note: Keep in mind about propertyAlthough you don’t have to have both a getter and a setter, you must have one of the two.

A property defined with both a getter and a setter is called a read-write property.

A property defined with only a getter is called a read-only property.

A property defined with only a setter is called a write-only property.

The Private data are manipulated indirectly by two ways.

The first method is using a pair of traditional accessor and mutator methods. Another method is using a named property.

The first method is, if you want the outside world to interact with your private usn data field, tradition dictates defining an accessor (get method) and mutator (set method).

Example 1: In this application, we have defined two methods set() and get(). The set() method mutator, set the value of usn variable. The get() method accessor, displays the value of the usn variable on the command prompt.

GetSetDemo.cs

using System;namespace Chapter4_Examples

{ class Student {string name, branch,usn; public void setusn(string sid){

usn = sid;}public string getusn(){

return usn;

Prepared By Namratha K

Page 107: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

107

}}class GetSetDemo

{ static void Main(){

Student st1 = new Student(); st1.setusn("1ST13MCA01"); Console.WriteLine("USN: " + st1.getusn()); Console.ReadKey();

}}

}

Another method is using a named property. Example :

using System;namespace

Chapter4_Examples{ class Student{

Chapter 4 Object- Oriented Programming with C#

string name, branch, usn;public string Studusn{

set{ usn = value; } get{return usn;}

}}class GetSetDemo1

{ static void Main(){

Student st1 = new Student(); st1.Studusn ="1ST13MCA01";Console.WriteLine("USN: " + st1.Studusn); Console.ReadKey();

}}

}

In the above example, we see the usage of Encapsulation by using properties. The property is composed using a get block(accessor) and set block(Mutator). The get block returns the value of the some property field. The set block sets the value of the some property field with the contents of “value” token. In the C# “value” keyword represents the right hand side of the assignment. The underlying data type of the value token depends on which sort of data it represents so that “value” token is called as object.

4.1.2 Internal representation of C# properties:

Many programmers tend to design traditional accessor and mutator methods using “get” and “set” prefixes (e.g., getName() and setName()). This naming convention itself is not problematic. However, it is important to understand that C# property is internally represented in CIL code using these same prefixes.

Example 3: Assume that class Student type has a private member variable named name, branch, usn to

Prepared By Namratha K

Page 108: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

108

represent an individual’s usn number, which is manipulated by a property named Studusn.

If you also define two methods named get_Studusn() and set_Studusn() to the above example as shown below: using System;

namespace Chapter4_Examples{ class Student {

string name, branch, usn;

public string Studusn{

set { usn = value; } get { return usn; }

}public void set_Studusn(string sid){

usn = sid;Chapter 4 Object- Oriented Programming with C#

}public string get_Studusn(){

return usn;}

}class

GetSetDemo2{ static void Main(){

Student st1 = new Student(); st1.Studusn = "1ST13MCA01";Console.WriteLine("USN: " + st1.Studusn); Console.ReadKey();

}}

}

In the above example, there is one property by name Studusn. This property internally represented as get_Studusn() and set_Studusn() methods as shown in figure. So, the compiler will generate an error if we explicitly include those methods in a class as shown below.

4.1.3 Write-Only Property:

Prepared By Namratha K

Page 109: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

109

Properties can be made write-only. This is accomplished by having only a set mutator in the property implementation.

Example 4:

class Student{string name, branch, usn;

public string Studusn{

set{usn = value;}}

}

In the above example, the property “Studusn” is having only set mutator but not get accessor. So we can callStudusn as a “write-only property”.

Chapter 4 Object- Oriented Programming with C#

4.1.4 Creating Read-Only Fields:

Properties can be made read-only. This is accomplished by having only get accessor in property implementation.

Example : using System;

namespace Class_Demos{ class Student{

string studusn;

public Student(){

studusn="1ST13MCA01";}public string Studusn{

get {return studusn;

}}

}

class ReadOnly{ static void Main(){

Student st1 = new Student(); Console.WriteLine("USN: " + st1.Studusn); Console.ReadKey();

}}

Prepared By Namratha K

Page 110: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

110

}

In the above example, the property “Studusn” is having only get accessor but not set mutator. So we can callStudusn as a “read-only property”.

4.1.5 “static” property:

C# also supports “static” properties. The static members are accessed at the class level, not from an instance (object) of that class. Static properties are manipulated in the same manner as static methods, as seen here:

For example , assume that the Student type defines a point of static data to represent the name of the institution studying these students. You may define a static property as follows:

using System;

namespace Class_Demos{

class Student{

string name, branch,

usn; static string Chapter 4 Object- Oriented Programming with C#

instName;public static string Institution{

set { instName = value; } get { return instName; }

}}class StaticProperty{

static void Main(){

Student.Institution = ""; Console.WriteLine("InstitutionName: " +Student.Institution); Console.ReadKey();

}}

}

4.2 Inheritance:

The next pillar of OOP, Inheritance provides you to reuse existing code and fast implementation time. The relationship between two or more classes is termed as Inheritance. In essence, inheritance allows you to extend the behavior of a base (or parent/super) class by enabling a subclass to inherit core functionality (also called a derived class/child class). All variables and methods in the base class can be called in the derived classes, provided they are declared public or protected.Inheritance comes in two ways:

Classical inheritance (the “is-a” relationship) Prepared By Namratha K

Page 111: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

111

Containment/delegation model (the “has-a” relationship).

4.2.1 Classical Inheritance(“is-a” Relationship):

When we establish “is-a” relationships between classes, we are building a dependency between types. The basic idea behind classical inheritance is that new classes may extend the functionality of other classes.

Example: Assume that we wish to define two additional classes to model Animal and Dog. The hierarchy looks like as shown below and we notice that Animal “is-a” Mammal, Dog IS-A Animal; Hence dog IS-A mammal as well.

Mammal

Animal

Dog

In “is-a” model, base classes are used to define general characteristics that are common to all subclasses and classes are extended by using “:” operator. The derived classes inherit the base class's properties and methods and clients of the derived class have no knowledge of the base class.Chapter 4 Object- Oriented Programming with C#

Example :

using System;namespace

Chapter4_Examples{ class Animal {

public Animal(){

Console.WriteLine("Base class constructor");}public void Greet(){

Console.WriteLine("Hello, I am kind of Animal");}

}

class Dog : Animal{ public Dog(){

Console.WriteLine("Derived class constructor");}

}class isademo{

static void Main(){

Dog d = new Dog(); d.Greet(); Console.ReadKey();

}}

Prepared By Namratha K

Page 112: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

112

}

In the above example, when the object d is created for the class Dog; the default constructor of a base class Animal is called automatically before the logic of the custom Dog constructor is executed. You will notice that even though we have not defined a Greet() method for the Dog class, it still knows how to greet us, because it inherits this method from the Animal class.

Do be aware that inheritance preserves encapsulation. Therefore, a derived class cannot directly access the private members defined by its base class.

4.2.2 Containment / Delegation model (“Has-A” Relationship):

The “HAS-A” relationship specifies how one class is made up of other classes.

Example 8: Consider we have two different classes Class1 and a Class2 when both of these entities share each other’s object for some work and at the same time they can exists without each other’s dependency (having their own life time) and there should be no single owner both have to be an independent from each other than type of relationship is known as "has-a" relationship i.e. Association.

Chapter 4 Object- Oriented Programming with C#

using System;

namespace Chapter4_Examples{

class Engine{public int horsepower; public void start(){

Console.WriteLine("Engine Started!");}

}class Car{

public string make;public Engine eng; //Car has an Engine public void start(){

eng.start();}

}class hasademo{

static void Main(){ Console.WriteLine("Manufacturing a Car");

Car mycar = new Car();mycar.make = "Toyoto";

Console.WriteLine("Manufacturing a Engine to start car"); mycar.eng = new Engine();mycar.eng.horsepower =220;

Console.WriteLine("\n*****Car Details*****");

Prepared By Namratha K

Page 113: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

113

Console.WriteLine("Brand: " + mycar.make); Console.WriteLine("Power: " + mycar.eng.horsepower); mycar.start();Console.Read();

}

Inheritance is of four types, which are as follows:

Single Inheritance: Refers to inheritance in which there is only one base class and one derived class. This means that a derived class inherits properties from single base class.

Hierarchical Inheritance: Refers to inheritance in which multiple derived classes are inherited from the same base class.

Multilevel Inheritance: Refers to inheritance in which a child class is derived from a class, which in turn is derived from another class.

Multiple Inheritance: Refers to inheritance in which a child class is derived from multiple base class.

C# supports single, hierarchical, and multilevel inheritance because there is only a single base class. It does not support multiple inheritance directly. To implement multiple inheritance, you need to use interfaces.Example :

Chapter 4 Object- Oriented Programming with C#

InherDemo.cs

using System; namespace Class_Demos{

class BaseClass{ public int dm;public void BCMethod(){

Console.WriteLine("I'm a Base Class Method");}

}

class DerivedClass:BaseClass{

public void DCMethod(){

Console.WriteLine("I'm a Derived Class Method");}

}class InherDemo{

static void Main(){

//Create a Base Class ObjectConsole.WriteLine("I'm accessing Base Class Object"); BaseClass bc = new BaseClass();bc.dm = 10; bc.BCMethod();//Create a Derived Class ObjectConsole.WriteLine("\nI'm accessing Derived Class

Prepared By Namratha K

Page 114: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

114

Object"); DerivedClass dc = new DerivedClass();dc.dm = 20; dc.BCMethod(); dc.DCMethod();Console.WriteLine("\nPress ENTER to quit..."); Console.Read();

}}

}

In this section, you learn about the following topics in the context of inheritance:Inheritance and Constructors Sealed classes and sealed methods Extension methods

4.2.3 Inheritance and Constructors:

As you know, a constructor is a special method of a class, which is used to initialize the members of the same class. A constructor is called by default whenever an object of a class is created. It is important to note that a Base class constructors are not inherited by derived classes. Thus we cannot instantiate a base constructor using derived class object, so we need the “base” keyword to access constructor of the base class from within a derived class.

Chapter 4 Object- Oriented Programming with C#

Example :

using System;

namespace Chapter4_Examples{public class A // It is the base class.{

protected int x; public A(int i){

x = i;Console.WriteLine("Base constructor A()");

}}public class B : A // This class derives from the previous class{

int y;public B(int i, int j): base(i){

y = j;Console.WriteLine("Derived constructor B()");

}public void show(){

Console.WriteLine("X= {0} \nY= {1}", base.x, y);}

}

class Basekeydemo

Prepared By Namratha K

Page 115: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

115

{ static void Main(){

B b = new B(10, 20); b.show(); Console.ReadKey();

}}

}

4.2.4 Sealed Classes and Sealed Method:

Sealed classes are classes that cannot be inherited. You can use the “sealed” keyword to define a class as a sealed class. The syntax if the declaring a sealed class is as follow:

sealed class <Class_name>{// data mebers and member functions

}

The following code snippet shows how to define a sealed class:

sealed class MyClass{. . . // data mebers public void GetDetail()

Chapter 4 Object- Oriented Programming with C#

{}public void ShowDetail(){}

}Class MainClass{

//Instantiation of myclass class //Method calling

}

When a base class is declared with sealed keyword, then that class cannot be extended. The sealed modifiers is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class, as shown in the following code snippet:

class DerivedClass: MyClass{} //Error

You will get the error message:

A sealed class can contain sealed methods. Similar to the sealed class, sealed method are also defined using the

Prepared By Namratha K

Page 116: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

116

“sealed” keyword. A derived class cannot override the sealed methods; however, you can use a sealed method to override an inherited virtual method with the same signature. It means that in methods, you always use sealed keyword with the combination of override keyword, as shown in the following code snippet:

class BaseClass{public virtual void SealedMethod(){

//Method Body}

}class DerivedClass: BaseClass{

public sealed override void SealedMethod(){

//Method Body}

}

Here, the sealed method SealedMethod() overrides the virtual method SealedMethod() defined in BaseClass class. Any derived class of DerivedClass class cannot further override theSealedMethod() method.

Chapter 4 Object- Oriented Programming with C#

Example :

using System;

namespace Class_Demos{

sealed class BClass{

public void method1(){

Console.WriteLine("This is method of Base class");}

}//Following lines shows compiler error as sealed class cannot be inherited

class DClass : BClass{}

class SealedDemo{

static void Main(){

BClass obj = new BClass(); obj.method1();Console.WriteLine("\nPress ENTER to quit..."); Console.Read();

}}}

Prepared By Namratha K

Page 117: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

117

4.2.5 Extension Method:

Extension method is a method that helps you to extend a class without creating a new derived class or modifying the original class. It works as a static method, but is invoked with an instance of the extended class. The extension method can be any static method which uses the “this” keyword before its first parameter.

Example :

using System;

namespace Class_Demos{

public static class Myclass{ //Defining extension method with

public static int myExtensionmethod(this string num) {

return (Int32.Parse(num)); } public static int Mystaticmethod(string num) {

return (Int32.Parse(num));}

Chapter 4 Object- Oriented Programming with C#

}

class ExtensionDemo{

static void Main(){

string num = "100";//invoking method of type extensionint ext = num.myExtensionmethod(); //Line AConsole.WriteLine("The output from myExtensionMethod()”+ext);

//invoking method of type staticint stat = Myclass.Mystaticmethod(num); //Line BConsole.WriteLine("The output from mystaticMethod()"+ stat); Console.Read();

}}

}

Output:

Differences between an extension method and a static method are as follows:

Extension Method Static MethodContain this keyword before the first argument Do not contain the this keyword in their argument

declarationWhen an extension method is called, the argument When a static method is called, you must pass alldeclared with the “this” keyword is not passed. the arguments. (see Line B in Program)

Prepared By Namratha K

Page 118: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

118

(see Line A in program)Extension method are defined in a static class only. It is not necessary that the static methods are

declared in a static class only

4.3 Polymorphism:

The final pillar of OOP is polymorphism. Polymorphism means one name many forms. Polymorphism defined as “one object behaving as multiple forms and one function behaves in different forms”. In other words, “Many forms of a single object is called Polymorphism”.

Advantages:

Allows you to invoke methods of a derived class through base class reference during runtime Provides different implementations of methods in a class that are called through the same name

There are two types of polymorphism, which are as follows:

Static polymorphism/Compile Time polymorphism/Early Binding/Overloading Dynamic polymorphism/Run-time polymorphism/Late Binding/Overriding

Chapter 4 Object- Oriented Programming with C#

4.3.1 Compile Time Polymorphism:

When a compiler compiles a program, it knows the information about the method arguments and accordingly, it binds the appropriate method to an object at the compile time itself. This process is called as Static polymorphism/Compile Time polymorphism/Early Binding/Overloading.

You can implement compile time polymorphism through overloaded methods in three types that are mention below:

Method overloading Operator overloading Indexer overloading

Method overloading:

In method overloading, you can be define many methods with the same name but different signatures. A method signature is the combination of the method’s name along with the number, type, and order of the parameters.

Example 13: In this application, the Area() method of Shape class is overloaded for calculating the area of square, rectangle, circle and triangle shapes. In the Main() method, the Area() method is called multiple times by passing different arguments.

using System;

namespace Class_Demos{

class Shape{

Prepared By Namratha K

Page 119: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

119

public void Area(int side){

Console.WriteLine("The area of Square is: " + side * side);}public void Area(int length, int breadth){

Console.WriteLine("The area of Rectangle is: "+ length * breadth);

}

public void Area(double radius){

Console.WriteLine("The area of Circle is: "+ 3.14 * radius * radius);

}Chapter 4 Object- Oriented Programming with C#

public void Area(double base1, double height){

Console.WriteLine("The area of Squate is: "+ (base1 * height)/2);

}}class MOverload{

static void Main()

{Shape shape = new Shape(); shape.Area(15); shape.Area(10, 20); shape.Area(10.5); shape.Area(15.5, 20.4); Console.Read();

}}

}

Operator Overloading:

The mechanism of assigning a special meaning to an operator according to user defined data type, such as classes or structs, known as operator overloading. The below table shows the list of operators and overloading status.

Table 4.1: operators and their overloading statusOperators Type Overloading Status

+, - , !, ++, --, true, false Unary Can be overloaded

+, - , *, /, %, &, |, ^, <<, >> Binary Can be overloaded

= =, !=, <, >, <=, >= Comparison Can be overloaded

&&, | | Conditional Logic Cannot be overloaded

[ ] Array Indexing Cannot be overloaded but can help in defining indexes

( ) CastCannot be overloaded but can help in defining new

Prepared By Namratha K

Page 120: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

120

conversion operators

+=, -=, *=, /=, %=, |=, ^=,Assignment Cannot be overloaded

<<=, >>=

=, , ?:, ->, new, is, sizeof, other Cannot be overloadedtypeof

When you overload an operator, you need to create a method that must be preceded by the “operator” keyword and that method should define as a static method.

Example: In this application, we have created a class, UnaryOpr, which contains a constructor, UnaryOpr, to initialize its two variables. The UnaryOpr class also contains the ShowData() method to display the value of the class variables and overload the functionality of the – (minus) operator. The – operator is overloaded by using the operator keyword. Next in the Main()method of the OpOverload class, the – Chapter 4 Object- Oriented Programming with C#

operator is used to show the negative value of an object of the UnaryOpr class.

using System;

namespace Class_Demos{class unaryopr

{int n1, n2;

public unaryopr() { }public unaryopr(int a, int b){n1 = a;

n2 = b;}

public void showData(){

Console.WriteLine("The numbers are: " +n1+ " and " +n2);}public static unaryopr operator -(unaryopr opr){

unaryopr obj = new unaryopr(); obj.n1 = -opr.n1;obj.n2 = -opr.n2; return obj;

}}class OpOverload{

static void Main(){

unaryopr opr1 = new unaryopr(20, 30); Console.WriteLine("Before Operator Overloading"); opr1.showData();unaryopr opr2 = new unaryopr();opr2 = -opr1; //invoke operator overloading method Console.WriteLine("After Operator Overloading"); opr2.showData();Console.Read();

}}}

Prepared By Namratha K

Page 121: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

121

Example : In this application, we have created a class, BinaryOpr, which contains a constructor, BinaryOpr, to initialize its two variables. The BinaryOpr class also contains the ShowData() method to display the value of the class variables and overload the functionality of the + (addition) operator. The + operator is overloaded by using the operator keyword. Next in the Main()method of the OpOverload1 class, the + operator is used to show the addition of the values of the objects of theBinaryOpr class.

using System;

namespace Class_Demos{

class Binaryopr{

Chapter 4 Object- Oriented Programming with C#

int n1, n2;public Binaryopr() { }public Binaryopr(int a, int b){

n1 = a;n2 = b;

}public void showData(){

Console.WriteLine("The numbers are: " + n1 + " and " + n2);

}public static Binaryopr operator

+(Binaryopr opr1, Binaryopr opr2){

Binaryopr obj = new Binaryopr(); obj.n1 = opr1.n1 + opr2.n1; obj.n2 = opr1.n2 + opr2.n2; return obj;

}}class BOverload{

static void Main(){

Binaryopr opr1 = new Binaryopr(20, 30); opr1.showData();

Binaryopr opr2 = new Binaryopr(30, 40); opr2.showData();

Binaryopr opr3 = new Binaryopr();opr3 = opr1 + opr2; //invoke operator overloading method

opr3.showData();Console.Read();

}}}

Prepared By Namratha K

Page 122: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

122

Indexer Overloading:

An indexer is used to treat an object as an array. It is used to provide index to an object to obtain values from the object.

Implementing an indexer requires you to use brackets ([ ]) with an object to get and set a value of the object. Indexer are declared as properties, with the difference that in case of indexers, you do not need to provide name to them. You need to use the “this” keyword to define an indexer.

Example 16: In this snippet, we have overloaded indexers by passing different type of parameters. We have defined two indexers, with the int type and string type parameters, named position and data, respectively. These indexers are used to display the values of different string data that is passed in the Main() method of the IndOverload class.

Chapter 4 Object- Oriented Programming with C#

using System;

namespace Class_Demos{

class MyClass{

string[] mydata; int arrsize;

public MyClass(int size){

arrsize = size;mydata = new string[size];

for (int i = 0; i < size; i++) mydata[i] = "DataValue";

}

public string this[int position]{

set{

mydata[position] = value;}get{

return (mydata[position]);}

}

public string this[string data]{

set{

for (int i = 0; i < arrsize; i++){

Prepared By Namratha K

Page 123: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

123

if (mydata[i] == data) mydata[i] = value;

}}get{

int count = 0;for (int i = 0; i < arrsize; i++){

if (mydata[i] == data) count = count + 1;

}return count.ToString();

}}

Chapter 4 Object- Oriented Programming with C#

}class IndOverload{

static void Main(){

int size = 10;MyClass obj = new MyClass(size);

obj[1] = "Hello"; obj[3] = "Good Morning"; obj[7] = "Welcome";obj["DataValue"] = "Have a nice day";

for (int i = 0; i < size; i++) Console.WriteLine("obj[{0}]: {1}", i, obj[i]);

Console.WriteLine("\n\nNumber of \"Have a nice day\" entries: {0}", obj["Have a nice day"]);

Console.Read();}

}}

4.3.2 Runtime Polymorphism / Overriding:

Overriding is a feature that allows a derived class to provide a specific implementation of a method that is already defined in a base class. The implementation of method in the derived class overrides or replaces the implementation of method in its base class. This feature is also known as runtime polymorphism because the compiler binds a method to an object during the execution of a program (runtime) instead of during the compilation of the program.

When you call a method, the method defined in the derived class is invoked and executed instead of the

Prepared By Namratha K

Page 124: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

124

one in the base class. To invoke the method of a derived class that is already defined in the base class, you need to perform the following steps:

Declare the base class method as virtual

Implement the derived class method using the override keyword

Example : We have created Bclass and Dclass classes, where the Dclass class is the derived class of the Bclass class. The Bclass class contain virtual method Show(). The Dclass class is overriding the Show() method of the base class by using the override keyword.

using System;

namespace Chapter4_Examples{public class Bclass

Chapter 4 Object- Oriented Programming with C#

{public virtual void Show(){

Console.WriteLine("Base Class");}

}

class Dclass : Bclass{

public override void Show(){

Console.WriteLine("Derived Class");}

}

class PolyDemo{

static void Main(string[] args){

// calling the overriden methodDclass objDc = new Dclass(); objDc.Show();// calling the base class methodBclass objBc = new Bclass(); objBc.Show();//Calling the overriden method because preference

will be right hand of ExerciseoperatorBclass obj = new Dclass(); obj.Show(); Console.ReadLine();

}}

}

Consider, you want to derive a class from a base class and to redefine some methods contained in this base class. In such a case, you cannot declare the base class method as virtual.

Then how you can override a method without declaring that method as virtual in the base class?

Prepared By Namratha K

Page 125: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

125

Ans: This can be possible with the new operator. The new operator is used to override the base class method in the derived class without using the virtual keyword. The new operator tells the compiler that the derived class method hides the base class method.

Example :

using System;

namespace Class_Demos{

public class Bclass{

public void Show(){

Console.WriteLine("Base Class");Chapter 4 Object- Oriented Programming with C#

}}

class Dclass : Bclass{

public new void Show(){

Console.WriteLine("Derived Class");}

}

class PolyDemo1{

static void Main(string[] args){

iii. calling the overriden method Dclass objDc = new Dclass(); objDc.Show(); iv.calling the base class method Bclass objBc = new Bclass(); objBc.Show(); //Calling Base Class Method objBc = new Dclass(); objBc.Show();Console.ReadLine();

}}

}

Output:

4.4 Abstraction:Prepared By Namratha K

Page 126: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

126

Abstraction is the process of hiding the details of a particular concept or object from a user and exposing only the essential features.

The characteristics of abstraction are as follows:Managing the complexity of the code Decomposing complex systems into smaller components

Let’s learn about the abstract classes and methods in detail.

4.4.1 Abstract Classes:

Classes can be declared as abstract by putting the keyword “abstract” before the class definitions.

Chapter 4 Object- Oriented Programming with C#

object of the class.

Example: public abstract class ShapeShape obj=new Shape();{

//Class Definition //Can’t be instantiated}

The Main purpose of the Abstract classes is to make classes that only represent base classes, and don’t want anyone to create objects of these class types. An abstract class cannot be instantiated because cannot create an

An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.

Example: public abstract class Shape{

public abstract void Draw();public void NonAbstractMethod(){

Console.WriteLine("NonAbstract Method");}

}

Characteristics:

Restricts instantiation, implying that you cannot create an object of an abstract class. Allows you to define abstract as well as non-abstract members in it Requires at least one abstract method in it Restrict the use of sealed keyword Possesses public access specifier; therefore, it can be used anywhere in a program.

4.4.2 Abstract Method:

Abstract methods have no implementation, so the method definitions is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods.

Prepared By Namratha K

Page 127: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

127

Syntax:public abstract void Draw();

Characteristics:

Restricts its implementation in an abstract derived class Allows implementation in a non-abstract derived class Requires declaration in an abstract class only Restrict declaration with static and virtual keywords Allows you to override a virtual method.

Chapter 4 Object- Oriented Programming with C#

Example :

using System;

namespace Chapter4_Examples{ abstract class absClass{//A Non abstract methodpublic int AddTwoNumbers(int Num1, int Num2){

return Num1 + Num2;}//An abstract method to be overridden in derived class public abstract int MultiplyTwoNumbers(int Num1,int Num2);

}

//A Child Class of absClass class absDerived:absClass{

//using override keyword,implementing the abstract method MultiplyTwoNumberspublic override int MultiplyTwoNumbers(int Num1,int Num2){

return Num1 * Num2;}

}

class AbstractDemo{static void Main(string[] args){

absDerived calculate = new absDerived(); int added = calculate.AddTwoNumbers(10,20);int multiplied = calculate.MultiplyTwoNumbers(10,20); Console.WriteLine("Added : {0}, Multiplied : {1}",

Prepared By Namratha K

Page 128: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

128

added,multiplied);Console.ReadLine();

}}

}

4.5 Interface:

“An interface is a collection of data members and member functions, but it does not implement them”.

Interface are introduced to provide the feature of multiple inheritance to classes. Multiple inheritance is the feature of OOP which allows a class to inherit from multiple classes. The methods defined in an interface do not have implementation, they only specify the parameters that they will take and the types of values they will return.Chapter 4 Object- Oriented Programming with C#

Characteristics:An interface is always implemented in a class. The class that implements the interface needs to implement all the members of the interface. You cannot instantiate an object through an interface An interface can have the same access modifiers as a class, such as public and private.

Syntax:interface <Interface_Name>{

//Abstract method declaration in interface body}

Example: public interface Channel

{void Next();

}

4.5.1 To implement multiple inheritance in a program, you need to use interfaces.

Example : Create an application named InterfaceDemo that shows how to implement an interface in a class.

using System;

namespace Class_Demos{

public interface Channel{

void Next(); void Previous();

}public interface Book{

Prepared By Namratha K

Page 129: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

129

void Next(); void Chapter();

}class InterfaceDemo:Channel,Book{

void Channel.Next(){

Console.WriteLine("Channel Next");}void Book.Next(){

Console.WriteLine("Book Next");}public void Previous(){

Console.WriteLine("Previous");Chapter 4 Object- Oriented Programming with C#

}public void Chapter(){

Console.WriteLine("Chapter");}static void Main(){

InterfaceDemo ind = new InterfaceDemo();((Book)ind).Next();//invoking Book method ind.Previous();ind.Chapter();Console.Read();

}}

}

Output

4.6 Interfaces and Inheritance:

When an interface is implemented by a base class, then the derived class of the base class automatically inherits method of the interface. You can initialize an object of the interface by type casting the object of the derived class with the interface itself.

Example 21: We have created two interface BaseInterface and DerivedInterface. The BaseInterface interface is inherited by the DerivedInterface interface. Then the

Prepared By Namratha K

Page 130: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

130

InterfaceImplemeter class implements the DerivedInterface interface.

using System;

namespace Class_Demos{

interface BaseInterface{

void GetPersonalDetail(); void GetContactDetail();

}interface DerivedInterface:BaseInterface{

void ShowDetail();}

Chapter 4 Object- Oriented Programming with C#

class InterfaceImplementer : DerivedInterface{

string name; long phonenum;public void GetPersonalDetail(){

Console.WriteLine("Enter your Name"); name = Console.ReadLine();

}public void GetContactDetail(){

Console.WriteLine("Enter your Phone Number"); phonenum = int.Parse(Console.ReadLine());

}

public void ShowDetail(){

Console.WriteLine("\nYour Details:"); Console.WriteLine("Name: " + name); Console.WriteLine("Phone Number: " + phonenum);

}}class InterfaceDemo1{

static void Main(){

InterfaceImplementer Myobj = new InterfaceImplementer();

Myobj.GetPersonalDetail();Myobj.GetContactDetail();Myobj.ShowDetail();Console.ReadLine();

}}}

Prepared By Namratha K

Page 131: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

131

Chapter 4 Object- Oriented Programming with C#

Assignment:

1. Explain encapsulation and its advantages. How encapsulation is achieved in C#?2. How method overriding different from method overloading?3. Write a C# program to overload ‘+’ and ‘++’ operators.4. Distinguish between compile time polymorphism and runtime polymorphism with suitable code

example5. Explain the following in detail with example i) virtual ii) Override iii) Readonly iv) Sealed6. Write a C# program to sort a list of numbers received from the command line. Incorporate exception

handling mechanism to handle the possible exceptional situations.7. How do you build Finalizable and Disposable object? Explain with relevant code and example8. What are Interfaces? How are they different from abstract classes?9. What is inheritance? Distinguish between “is a” and “has a” relationships in C#.10. How would you enforce encapsulation using accessors and mutators? Explain with suitable code.

Prepared By Namratha K

Page 132: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

132

Chapter 5 Delegates Events and Exception

DELEGATES EVENTS AND EXCEPTION

5.1 Definition:A delegate is special type of object that contains the details of a method rather than data. OR

A delegate is a class type object, which is used to invoke a method that has been encapsulated into it at the time of its creation.

A delegate is a reference type variable that holds the references to a method of any class. Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.

Uses: Suppose you need to create a program that requires data, such as student information, to display it on a website. This data can be retrieved by calling a method without having to know to compiler time which method is to be invoked. In this case, you need to create an object of delegate and encapsulate a reference to that method inside the delegate object.

5.2 Creating and Using Delegates:

Following are the four steps to create and use a delegate in your program:

Declaring a delegate

Defining delegate methods

Creating delegate objects

Invoking delegate objects

Declaring a delegate:

A delegate represents a class type, it can be declared at any place where a class can be defined – outside all classes or inside a class. A delegate can be declared using the following syntax:

Access-modifier delegate <return-type> Prepared By Namratha K

Page 133: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

133

delegate_name(arg1, arg2, … argn);Where,

Access-modifier- the modifier that controls the accessibility of the delegate and can be public, private, protected or internal.delegate – is a keyword indicates the declaration belongs to a delegate return-type - is the return-type of the delegatedelegate-name – is the name of the delegateParameter-list – the list of parameter that the delegate takes.

Example: public delegate void Compute(int x, int y);Defining delegate methods:

A delegate method is any method whose signature matches the delegate signature exactly. It can be either static or an instance method.

Example: Define a static method, named add() to be encapsulated into the Compute delegate as follows:Chapter 5 Delegates Events and ExceptionChapter 5 Delegates Events and Exception

public static void add(int x, inty){

Console.WriteLine(“Sum= {0}”, a+b);}

Define a static method, named subtract() to be encapsulated into the Compute delegate as follows:

public void subtract(int x, inty){

Console.WriteLine(“Subtract= {0}”, a-b);}

5.2.1 Creating delegate objects:

You can create an object of a delegate using the following syntax:

Delegate-name object-name = new Delegate-name(expression);Where,

delegate-name: is the name of the delegate declared object-name: is the name of the delegate objectexpression: what you want to encapsulate into the delegate object and it can be name of the method or instance of the delegate type.

Example: delegate object type is created to hold reference of static add() method.

Compute cmp1 = new Compute(MyDelegate.add); delegate object type is created to hold reference of instance subtract() mehtod.

MyDelegte mdt= new MyDelegate();

Compute cmp2 = new Compute(mdt.subtract);

5.2.2 Creating delegate objects:

A delegate object is invoked as a method is invoked.

Prepared By Namratha K

Page 134: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

134

Syntax:delegate-object(argument-list);

Where,delegate-object – the name of the object being invoked;

argument-list – is the list of values that is assigned to the parameters of the method, encapsulated into the delegate object.

Example: DelegatesDemo.csusing System;public delegate int Operation(int p, int q);namespace Class_Demos{

class DelegatesDemo{Chapter 5 Delegates Events and Exception

public static int AddNum(int p, int q){

return (p+q);}public int MultNum(int p, int q){

return (p*q);}

static void Main(){

//create delegate instances for calling static method Operation op1 = new Operation(AddNum);//calling the methods using the delegate objects Console.WriteLine("Value of Num1: {0}", op1(10,20));//create delegate instances and class object for

calling method

DelegatesDemo dd = new DelegatesDemo(); Operation op2 = new Operation(dd.MultNum); //calling the methods using the delegate objectsConsole.WriteLine("Value of Num2: {0}", op2(5,2));Console.ReadKey();

}}}

Output:

5.3 Multicasting with Delegates:A delegate object to hold references of and invoke multiple methods. Such objects are called multicast delegates or combinable delegates. You can encapsulate more than one method into a single delegate object using the overloaded += operator.

Prepared By Namratha K

Page 135: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

135

Example: sample s1=new sample(m.add);s1 += m.sub;s1 += m.mul;

Delegate object satisfy the following two conditions can be made as multicast delegates:

ii. The return type of the delegate is void

iii. None of the parameters of the delegate is an output parameter but a parameter declared using the out keyword.

Example:

using System; namespace Class_Demos{

delegate void sample(int a,int b); Chapter 5 Delegates Events and Exception

class MCDelegates{void add(int n1, int n2){

Console.WriteLine(n1+ "+" +n2+ "=" + (n1 + n2));}void mul(int n1, int n2){

Console.WriteLine(n1 + "*" + n2 + "=" + (n1 * n2));}void sub(int n1, int n2){

Console.WriteLine(n1 + "-" + n2 + "=" + (n1 - n2));}static void Main(){

MCDelegates m=new MCDelegates(); sample s1=new sample(m.add);s1 += m.sub;s1 += m.mul;

s1(10, 20); Console.ReadKey();

}}

}

Output:

Prepared By Namratha K

Page 136: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

136

5.3.1 Exploring Covariance and Contravariance:

Covariance allows you to create delegate methods which are used by classes and derived classes.

OR

Covariance means that if a delegate is declared to return a base type, an instance can be created using a method which is declared to return a type derived from it.

Example:

delegate object methods(args…….)

The preceding statement defines a delegate, methods(), Covariance allows the methods() delegate to point to any method that takes a arguments irrespective of its return type, as all types of .NET inherit from the System.Object class. Therefore, the methods() delegate can point to the method in the class as shown in the following code:

Chapter 5 Delegates Events and Exception

int Getadd(int a ){ return(a+b);

}

Advantages:

To increase the flexibility while matching delegate methods with delegate signatures.[flexibility means the ability of a delegate to cope up with different classes or events of a program.]

Example:CovarianceDemo.cs

using System;

namespace Class_Demos{

class Animal{

public Animal CreateA(){

Console.WriteLine("This is Base class Animal "); return new Animal();

}}

class Dog:Animal{

public Dog CreateD(){

Console.WriteLine("This is Derived class Dog "); return new Dog();

}}

class CovarianceDemo{

public delegate Animal Create(); public static void Foo(Create obj)

Prepared By Namratha K

Page 137: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

137

{obj();

}

public static void Main(){

Create obj1 = new Create(new Animal().CreateA); Create obj2 = new Create(new Dog().CreateD); Foo(obj1);Foo(obj2);Console.ReadKey();

}}

}

Chapter 5 Delegates Events and Exception

Contravariance allows you to use a method with derived parameters as a delegate. This means that contravaiance enables a delegate to point to a method whose argument is the base type of argument appearing in the delegate’s signature.

OR

Contravariance means that if a delegate parameter is declared to be a derived type, an instance can be created using a method which has a base type for that parameter.

Example: In this application, we have declared a delegate, Create, having a parameter of type Dog, which is derived from the delegate signature parameter type. The Create delegate can point to the method1 methodbecause parameter types of Method1 are the base types for the Dog class specified on the delegate signature.

ContravarianceDemo.cs

using System;

namespace Class_Demos{

class Animal{public void CreateA(){

Console.WriteLine("This is Base class Animal ");}

}

class Dog : Animal{ public void CreateD()

{Console.WriteLine("This is Derived class Dog ");

}}

class ContravarianceDemo{

public delegate Animal Create(Dog d); public static Animal method1(Animal a1)

Prepared By Namratha K

Page 138: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

138

{a1.CreateA(); return a1;

}public static Animal method2(Dog a2){

a2.CreateD();a2.CreateA(); return a2;

}public static void Main(){

//Contravariance allows this delegateCreate obj1 = method1; Create obj2 = method2;

Chapter 5 Delegates Events and Exception

//Invoke methods through the delegate object Console.WriteLine(obj1(new Dog())); Console.WriteLine(obj2(new Dog()));

Console.WriteLine("Press ENTER to quit..\n"); Console.ReadKey();

}}

}

5.4 Exploring Anonymous methods with Delegates:

Anonymous methods allow you to instantiate a delegate and create a code block, which is passed to the delegate as a delegate parameter. This code can be executed by a delegate, when it is called.

Example: The below code shows how to define a named method:

//Declaring a delegateDelegate void delg(int a);//Defining a named method; void func(int n){}//Instantiating the delegate using the named method as a parameter;Delg d=obj.func;

In this code, We have instantiated the delegate, delg, by using the named method, func(), as a parameter. Now, we instantiate the delegate using the anonymous method:

//Declaring a delegateDelegate void delg(int a);

//Instantiating the delegate using an anonymous method as a parameter;Delg d=delegate(int n){ };

Prepared By Namratha K

Page 139: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

139

The following points to remember while working with anonymous method:Do not use unsafe code in an anonymous method.

Do not use any return type other than void.

You need to define an anonymous method in-line and not as a class member, while invoking a delegate.

Do not use statements that transfer the control outside the anonymous block, such as goto, break, or continue. You cannot use these statements outside the anonymous method but can be define inside the anonymous method.

Do not access the ref or out parameter of an outer scope using the anonymous method because the variable or parameters whose scope contains the anonymous method declaration are said to be in the outer scope of the anonymous method.

Chapter 5 Delegates Events and Exception

Example:

AnonymousDemo.cs

using System;delegate void ExampleAnonyms(string str); delegate void ExampleAnonyms1();

namespace Class_Demos{ class AnonymousDemo{

static void Main(){ExampleAnonyms p1 = delegate(string str1){

Console.WriteLine(str1);};//calling delegate using anonymous method as a parameter p1("This is an example of an anonymous method");

ExampleAnonyms1 p2 = delegate(){Console.WriteLine("This is an example of an anonymous method"); Console.WriteLine("Press

ENTER to quit...");Console.Read();

};//calling delegate using anonymous method p2();

}}

}

5.6 Events:

An event is a delegate type class member that is used by an object or a class to provide a notification to other objects that an event has occurred. The “event” keyword can be used to declare an event, as shown in the

Prepared By Namratha K

Page 140: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

140

following syntax:Syntax:

Where,Access-Modifier – is the modifier that determines the accessibility of the event event – is a keywordtype – type of event, which should necessarily be a delegate type event-name – valid c# identifier.

You need to define a method to listen and handle the event and then bind this method to the event using the overloaded += operator as follows.

Class-objectevent-name += new class-objectdelegate-name(method-name);

You need to detach from a source of events, you can use -= operator as follows:

Class-objectevent-name -= new class-objectdelegate-name(method-name);

Chapter 5 Delegates Events and Exception

Example: This application, named EventHandlerDemo, where you find a simple event source object. This object contains a given internal member variable that can be set using a member function. Each time this member variable is changed, the event source fires an event to notify any listeners that changes are pending. If no event handlers are defined, the event source notifies about that too.

EventsDemo.cs

using System;

namespace Class_Demos{ class EventTestClass{

//The value to track int nvalue;

//Allow a handler for the eventpublic delegate void ValueChangedEventHandler();

//This is the event itselfpublic event ValueChangedEventHandler Changed;

//This method is used to fire the event protected virtual void onChanged(){

if (Changed != null) Changed();

elseConsole.WriteLine("Event fired. No handler");

}public EventTestClass(int nvalue){

SetValue(nvalue);}

Prepared By Namratha K

Page 141: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

141

public void SetValue(int nv){

if (nvalue != nv){

nvalue = nv;onChanged(); //Fire the event

}}}

class EventsDemo{

static void Main(){

EventTestClass etc = new EventTestClass(3); etc.SetValue(5);etc.SetValue(5);etc.SetValue(3);

Console.WriteLine("\nPress ENTER to quit..."); Chapter 5 Delegates Events and Exception

Console.ReadLine();}

}}

As you can see, the event handler is called three times. When you call the SetValues method second time, the event is not fired because the value (which was 5) does not change.Output:

When you talk about events, the equation always has two tasks that as follows below.

4) An event source pays attention to firing events and then detects the timing when an event should be fired.

5) The event handler deals with receiving the information that an event has fired and then verifies the information that the event is present.

Event Source:

Event source is an object that inform other objects that something has changed.

Event Handler:

Event handler receive event notifications. When an event source notifies that an event is called, all the event handlers that have registered for the notification of that event start executing.

An event handler may be either a static or a non-static method of a class. In case of a static method, event handlers simply respond to a given event source and take a course of action based on the information passed to the handler.Prepared By Namratha K

Page 142: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

142

Example:

EventHandlerDemo.cs

using System;

namespace Class_Demos{

public delegate void EventHandler(); class EventHandlerDemo{

public static event EventHandler _show;

static void Main(){

Chapter 5 Delegates Events and Exception

1)Add event handlers to Show event. _show += new EventHandler(Dog); _show += new EventHandler(Cat); _show += new EventHandler(Mouse); _show += new EventHandler(Mouse);

2) Invoke the event. _show();

Console.Read();}

static void Cat(){

Console.WriteLine("Cat");}

static void Dog(){

Console.WriteLine("Dog");}

static void Mouse(){

Console.WriteLine("Mouse");}

}}

Output:

Prepared By Namratha K

Page 143: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

143

5.6.1 Multiple Event Handler:

Like delegates, events can be multicast. This enables multiple objects to respond to an event notification, you used the += operator to add the event handler. Here is an event multicast example:

MultiEventDemo.cs

using System;

namespace Class_Demos{

class EventTestClass{

//The value to track int nvalue;

Chapter 5 Delegates Events and Exception

//Allow a handler for the eventpublic delegate void ValueChangedEventHandler();

//This is the event itselfpublic event ValueChangedEventHandler Changed;

//This method is used to fire the event protected virtual void onChanged(){

if (Changed != null) Changed();elseelse

Console.WriteLine("Event fired. No handler");}

public EventTestClass(int nvalue){

SetValue(nvalue);}

public void SetValue(int nv){

if (nvalue != nv){

nvalue = nv;onChanged(); //Fire the event

}//else// Console.WriteLine("No Fire");

}}

class MultiEventDemo{

public void HandleChange1(){

Prepared By Namratha K

Page 144: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

144

Console.WriteLine("Handler 1 called");}

public void HandleChange2(){

Console.WriteLine("Handler 2 called");}static void Main(){

EventTestClass etc = new EventTestClass(3);

MultiEventDemo med = new MultiEventDemo(); //Create a handler for this class etc.Changed += new

EventTestClass.ValueChangedEventHandler(med.HandleChange1); etc.Changed+= new

EventTestClass.ValueChangedEventHandler(med.HandleChange2);Chapter 5 Delegates Events and Exception

etc.SetValue(5);etc.SetValue(5);etc.SetValue(3);

Console.WriteLine("\nPress ENTER to quit..."); Console.ReadLine();

}}}

The most interesting part of this application is the OnChanged event, which is highlighted in the code. Notice that this event source does not know about how many event handlers are defined for this particular event. The event source simply calls the delegate function. However, when you run the program, you see that both event handlers are called by the application. This process happens by the internal logic of the delegate mechanism, which chains together the event handlers behind the scenes.

5.7 Exception Handling:An exception is a problem that arises during the runtime (execution of a program) such as division of a number by zero, passing a string to a variable that holds an integer value.

C# exception handling is built upon four keywords: try, catch, finally, and throw.

try: A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.

catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

Example:

ExcepDemo.cs

using System;

Prepared By Namratha K

Page 145: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

145

namespace Class_Demos{

class ExcepDemo{

static void Main(string[] args){

int div=0, number=10; try{

div = 100 / number;}catch (DivideByZeroException ex){

Console.WriteLine("Exception occured : " + ex.Message);}finally

Chapter 5 Delegates Events and Exception

{Console.WriteLine("Result is: {0}", div); Console.WriteLine("\nPress ENTER to Quit..."); Console.ReadKey();

}}

}}

throw: A program throws an exception when a problem shows up. This is done using a throw keyword. The throw statement takes only a single argument to throw the exception. When a throw statement is encountered, a program terminates. In the following snippet, you can see that we have thrown a new DivideByZeroException explicitly.

try{

throw new DivideByZeroException();}catch{

Console.WriteLine(“Exception”);}

Example:

ThrowStat.cs

using System;

namespace Class_Demos{

class ThrowStat{

static void Main(string[] args){

Prepared By Namratha K

Page 146: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

146

int number; Console.WriteLine("Enter a number");number = int.Parse(Console.ReadLine()); try{

if (number > 10)throw new Exception("OutofSize");

}catch (Exception ex){

Console.WriteLine("Exception occured : " + ex.Message);

}finally{

Console.WriteLine("This is last statment"); Console.WriteLine("\nPress ENTER to Quit...");

Chapter 5 Delegates Events and Exception

Console.ReadKey();}

}}

}

5.7.1 Exception Classes in C#:

C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from theSystem.Exception class are the System.ApplicationException and System.SystemException classes.

The System.ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class.

The System.SystemException class is the base class for all predefined system exception.

The following table provides some of the predefined exception classes derived from theSytem.SystemException class:

Exception Class Description

AccessExceptionOccurs when a type member, such as a variable, cannot be accessed

ArgumentException Defines an invalid argument to a method

ArgumentNullException Occurs if null argument is passed to a method that does not accept itArgumentOutofRangeException Occurs if an argument value is not within a range

ArithmeticExceptionOccurs if an Arithmetic overflow or Arithmetic underflow has occurred

Prepared By Namratha K

Page 147: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

147

ArrayTypeMismatchException Occurs if you try to store the incorrect type of object in an array

BadImageFormatException Occurs when the image file of a DLL file or an executable program is

invalid

DivideByZeroException Occurs if you try to divide a number by zero

FormatException Occurs if there is an incorrect format of argument

IndexOutOfRangeException Occurs if the index of an array is out of bond

InvalidCastExpression Occurs if you try to cat an object to an invalid class

InvalidOperationExceptionOccurs if a method call is invalid for the current state of the object

MissingMemberExceptionOccurs if you try to dynamically access a member of a class that does not

exist

NotFiniteNumberException Occurs if a number is invalid or infinite

NotSupportedException Occurs when a method that is invoked is not supported

NullReferenceException Occurs if you try to make use of an unassigned reference

OutOfMemoryException Occurs if an execution stops due to lack of memory

StackOverflowExceptionOccurs if a stack overflow

5.8 Checked and Unchecked Statements:“checked” and “unchecked” statements are used to check the memory overflow exceptions.

The “checked” keyword is used to check the overflow for integral-type arithmetic operations and conversions. Overflow occurs when the value of a variable exceeds the required original length of the variable.

The “unchecked” keyword ignores the overflow-checking of the integral-type arithmetic operations and conversions. Arithmetic overflow is ignored and the program displays the truncated integers from the result.

Example: You can see that we have taken two byte type variables num1 and num2 and assign the value 127 to both of them. In the try block, the result of multiplication of both the variables is stored in another byte type variable, result. As the multiplication of values stored in num1 and num2 variable exceeds the limit of the value that can be stored in the result variable; therefore an exception occurs.

In this case, the checked statement causes the overflow exception and displays the exception message; however, the unchecked statement does not cause any exception and displays the result.

using System;

namespace Class_Demos{

Prepared By Namratha K

Page 148: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

148

class CheckUnDemo{

static void Main(){

byte num1, num2, result; num1 = 127;num2 = 127; try {

result=unchecked((byte)(num1 * num2)); Console.WriteLine("Unchecked result:" + result);

result=checked((byte)(num1 * num2)); Console.WriteLine("Checked result:" + result);}

catch(OverflowException ex){

Chapter 5 Delegates Events and Exception

Console.WriteLine("Exception occured:" + ex.Message);}finally{

Console.WriteLine("Press Enter to Quit..."); Console.ReadLine();

}}

}}

Prepared By Namratha K

Page 149: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

149

Chapter 5 Delegates Events and Exception

Assignment

1. What are delegates? Explain creation and usage of delegates.2. Write a short notes on : i) Events ii) Event sources iii) Event handlers iv) Event delegates.3. What are the checked and unchecked statements?4. What are delegates? Explain with code example, the concept of multicasting with delegates.5. Explain exception handling with a sample program to handle multiple exceptions6. Explain the concepts of events in C# with suitable code and example.

Prepared By Namratha K

Page 150: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

150

Chapter 6 Graphical user interface

Graphical user interface

6.1 Introduction:

A graphical user interface (GUI) allows a user to interact visually with a program. A GUI gives a program a distinctive “look” and “feel.”

example of a GUI:

Fig. 1: Example for GUI

GUIs are built from GUI controls (which are sometimes called components or widgets— short for window gadgets). GUI controls are objects that can display information on the screen or enable users to interact with an application via the mouse, keyboard or some other form of input (such as voice commands). Several common GUI controls are listed in Fig. 2—in the sections that follow and in Chapter 15, we discuss each of these in detail.

Prepared By Namratha K

Page 151: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

151

Control Description

Fig 2. Some basic GUI controls

Chapter 6 Graphical user interface

6.2 Windows Forms:

Windows Forms are used to create the GUIs for programs. A Form is a graphical element that appears on your computer’s desktop; it can be a dialog, a window or an MDI window (multiple document interface window). A component is an instance of a class that implements the IComponent interface, which defines the behavior that components must implement, such as how the component is loaded. A control, such as a Button or Label, has a graphical representation at runtime. Some components lack graphical representations (e.g., class Timer of namespace System.Windows.Forms). Such components are not visible at run time.Figure.3 displays the Windows Forms controls and components from the C#Toolbox. The controls and components are organized into categories by functionality.

Selecting the category All Windows Forms at the top of the Toolbox allows you to view all the controls and components from the other tabs in one list (Fig. 3).

Prepared By Namratha K

Page 152: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

152

Fig 3: Toolbox

A Form is a container for controls and components. When you drag items from the Toolbox onto the Form, Visual Studio generates code that creates the object and sets its basic properties. This code is updated when the control or component’s properties are modified in the IDE. Removing a control or component from the Form deletes the corresponding generated code. The IDE maintains the generated code in a separate file using partial classes—classes that are split among multiple files and assembled into a single class by the compiler.

Chapter 6 Graphical user interface

Each control or component we present in this chapter is located in namespaceSystem.Windows.Forms. To create a Windows application, you generally create a Windows Form, set its properties, add controls to the Form, set their properties and implement event handlers (methods) that respond to events generated by the controls. Figure 4 lists common Form properties, methods and a common event.

Prepared By Namratha K

Page 153: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

153

Fig. 4: Common Form properties, methods and an event

6.3 A Simple Event Driven GUI:

The Form in the application below program contains a Button that a user can click to display a MessageBox. In line 6, notice the namespace declaration, which is inserted for every class you create. We’ve been removing these from earlier simple examples because they were unnecessary.

Namespaces organize groups of related classes. Each class’s name is actually acombination of its namespace name, a dot (.) and the class name. This is known as the class’s fully qualified class name.

Chapter 6 Graphical user interface

Prepared By Namratha K

Page 154: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

154

Delegates and the Events Handling Mechanism:The control that generates an event is known as the event sender. An event-handling method—known as the event handler—responds to a particular event that a control generates.When the event occurs, the event sender calls its event handler to perform a task(i.e., to “handle the event”). The .NET event-handling mechanism allows you to choose your own names for event-handling methods. However, each event-handling method must declare the proper parameters to receive information about the event that it handles. Since you can choose your own method names, an event sender such as a Button cannot know in advance which method will respond to its events. So, we need a mechanism to indicate which method is the event handler for an event.

6.3.1 Delegates

Event handlers are connected to a control’s events via special objects called delegates. A delegate object holds a reference to a method with a signature that is specified by the delegate type’s declaration. GUI

Chapter 6 Graphical user interface

controls have predefined delegates that correspond to every event they can generate. For example, the delegate for a Button’s Click event is of type EventHandler (namespace System). If you look at this type in the online help documentation, you’ll see that it’s declared as follows:

Prepared By Namratha K

Page 155: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

155

public delegate void EventHandler( object sender, EventArgs e );

This uses the delegate keyword to declare a delegate type named EventHandler, which can hold references to methods that return void and receive two parameters—one of type object (the event sender) and one of type EventArgs. If you compare the delegate declaration with clickButton_Click’s header , you’ll see that this event handler indeed meets the requirements of the EventHandler delegate. The preceding declaration actually creates an entire class for you. The details of this special class’s declaration are handled by the compiler.

6.3.2 Indicating the Method that a Delegate Should Call:

An event sender calls a delegate object like a method. Since each event handler is declared as a delegate, the event sender can simply call the appropriate delegate when an event occurs— a Button calls the EventHandler delegate that corresponds to its Click event in response to a click. The delegate’s job is to invoke the appropriate method. To enable the clickButton_Click method to be called, Visual Studio assigns clickButton_Click to the delegate,

new System.EventHandler(this.clickButton_Click);

6.3.3 Control Properties and Layout:

The Select method transfers the focus to a control and makes it the active control.When you press the Tab key in an executing Windows application, controls receive the focus in the order specified by their TabIndex property. This property is set by Visual Studio based on the order in which controls are added to a Form, but you can change the tabbing order. TabIndex is helpful for users who enter information in many controls, such

Chapter 6 Graphical user interface

Prepared By Namratha K

Page 156: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

156

Fig. 6: Class control properties and methods

as a set of TextBoxes that represent a user’s name, address and telephone number. The user can enter information, then quickly select the next control by pressing the Tab key. The Enabled property indicates whether the user can interact with a control to generate an event. Often, if a control is disabled, it’s because an option is unavailable to the user at that time. For example, text editor applications often disable the “paste” command until the user copies some text. In most cases, a disabled control’s text appears in gray (rather than in black). You can also hide a control from the user without disabling the control by setting the Visible property to false or by calling method Hide. In each case, the control still exists but is not visible on the Form.

6.3.4 Anchoring and Docking:

You can use anchoring and docking to specify the layout of controls inside a container (such as a Form). Anchoring causes controls to remain at a fixed distance from the sides of the container even when the container is resized. Anchoring enhances the user experience.

Chapter 6 Graphical user interface

Prepared By Namratha K

Page 157: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

157

For example, if the user expects a control to appear in a particular corner of the application, anchoring ensures that the control will always be in that corner—even if the user resizes the Form. Docking attaches a control to a container such that the control stretches

Fig 7: Control layout properties.

6.3.5 Labels, TextBoxes and Buttons:

Labels provide text information (as well as optional images) and are defined with class Label(a derived class of Control). A Label displays text that the user cannot directly modify.

A Label’s text can be changed programmatically by modifying the Label’s Textproperty. Figure 8 lists common Label properties.

Fig 8: Common Label properties.

A textbox (class TextBox) is an area in which either text can be displayed by a program or the user can type text via the keyboard. A password TextBox is a TextBox that hides the information entered by the user. As the user types characters, the password TextBox masks the user input by displaying a password character. If you set the property UseSystemPasswordChar to true, the TextBox becomes a password TextBox. Users often encounter both types of TextBoxes, when logging into a computer or website—the username TextBox

Prepared By Namratha K

Page 158: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

158

Chapter 6 Graphical user interface

allows users to input their usernames; the password TextBox allows users to enter their passwords. Figure 9 lists the common properties and a common event of TextBoxes.

Fig 9: TextBox properties and an event.

A button is a control that the user clicks to trigger a specific action or to select anoption in a program. As you’ll see, a program can use several types of buttons, such as checkboxes and radio buttons. All the button classes derive from class ButtonBase (namespace System.Windows.Forms), which defines common button features. Button, which typically enables a user to issue a command to an application. Figure 10 lists common properties and a common event of class Button.

Fig. 10: Button properties and an event.

Prepared By Namratha K

Page 159: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

159

Chapter 6 Graphical user interface

6.4 GroupBoxes and Panels:

GroupBoxes and Panels arrange controls on a GUI. GroupBoxes and Panels are typically used to group several controls of similar functionality or several controls that are related in a GUI. All of the controls in a GroupBox or Panel move together when the GroupBox or Panel is moved. Furthermore, a GroupBoxes and Panels can also be used to show or hide a set of controls at once. When you modify a container’s Visible property, it toggles the visibility of all the controls within it.

The primary difference between these two controls is that GroupBoxes can display a caption (i.e., text) and do not include scrollbars, whereas Panels can include scrollbars and do not include a caption. GroupBoxes have thin borders by default; Panels can be set so that they also have borders by changing their BorderStyle property. Figures 11– 12 list the common properties of GroupBoxes and Panels, respectively.

Fig.11: GroupBox properties.

Fig. 12: Panel propertiesChapter 6 Graphical user interface Chapter 6 Graphical user interface

6.5 CheckBoxes and RadioButtons:

C# has two types of state buttons that can be in the on/off or true/false states—CheckBoxes and RadioButtons. Like class Button, classes CheckBox and RadioButton are derived from class ButtonBase.

6.5.1 CheckBoxesA CheckBox is a small square that either is blank or contains a check mark. When the user clicks a CheckBox to select it, a check mark appears in the box. If the user clicks the CheckBox again to deselect it, the check mark is removed. You can also configure a CheckBox to toggle between three states (checked, unchecked and indeterminate) by setting its Three- State property to true. Any number of CheckBoxes can be selected at a time. A list of common CheckBox properties and events appears in Fig. 13

Prepared By Namratha K

Page 160: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

160

Fig 13: CheckBox properties and events.

6.5.2 ToolTips:

Figure 14 describes common properties and a common event of class ToolTip.

Chapter 6 Graphical user interface

Prepared By Namratha K

Page 161: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

161

Fig 14: ToolTip properties and an event.

When you add a ToolTip component from the Toolbox, it appears in the component tray—the gray region below the Form in Design mode. Once a ToolTip is added to a Form, a new property appears in the Properties window for the Form’s other controls. This property appears in the Properties window as ToolTip on, followed by the name of the ToolTip component.

For instance, if our Form’s ToolTip were named helpfulToolTip, you would set a control’s ToolTip on helpfulToolTip property value to specify the control’s tool tip text. Figure 14.32 demonstrates the ToolTip component. For this example, we create a GUI containing two Labels, so we can demonstrate different tool tip text for each Label. To make the sample outputs clearer, we set the BorderStyle property of each Label to FixedSingle, which displays a solid border. Since there’s no event-handling code in this example, we did not show the code for the Form class.

6.6 Mouse-Event Handling:

Mouse events can be handled for any control that derives from class System. Windows.Forms.Control. For most mouse events, information about the event is passed to the event-handling method through an object of class MouseEventArgs, and the delegate used to create the mouseevent handlers is MouseEventHandler. Each mouse-event-handling method for these events requires an object and a MouseEventArgs object as arguments. Class MouseEventArgs contains information related to the mouse event, such as themouse pointer’s x- and y-coordinates, the mouse button pressed (Right, Left or Middle) and the number of times the mouse was clicked. The x- and y-coordinates of the Mouse- EventArgs object are relative to the control that generated the event—i.e., point (0,0) represents the upper-left corner of the control where the mouse event occurred. Several common mouse events and event arguments are described in Fig. 15

Chapter 6 Graphical user interface

Prepared By Namratha K

Page 162: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

162

Fig 15: Mouse events and event arguments.

Below program uses mouse events to draw on a Form. Whenever the user drags the mouse (i.e., moves the mouse while a mouse button is pressed), small circles appear on the Form at the position where each mouse event occurs during the drag operation.

using System;using System.Drawing;using System.Windows.Forms;namespace Painter{// creates a Form that is a drawing surface public partial class PainterForm : Form { bool shouldPaint = false; // determines whether to paint

// default constructor public PainterForm() { InitializeComponent(); } // end constructor

// should paint when mouse button is pressed down private void PainterForm_MouseMove( object sender, MouseEventArgs e ) {// indicate that user is dragging the mouseChapter 6 Graphical user interface Prepared By Namratha K

Page 163: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

163

shouldPaint = true; } // end method PainterForm_MouseDown

// stop painting when mouse button is released private void ( object sender, MouseEventArgs e ) {// indicate that user released the mouse buttonshouldPaint = false; } // end method PainterForm_MouseUp

// draw circle whenever mouse moves with its button held down private void ( object sender, MouseEventArgs e ) {if ( shouldPaint ) // check if mouse button is being pressed{// draw a circle where the mouse pointer is presentusing ( Graphics graphics = CreateGraphics() ){graphics.FillEllipse(new SolidBrush( Color.BlueViolet ), e.X, e.Y, 4, 4 );} // end using; calls graphics.Dispose()} // end if } // end method PainterForm_MouseMove } // end class PainterForm } // end namespace Painter

PainterForm_MouseDown// indicate that user is dragging the mouseshouldPaint = true;PainterForm_MouseUp// indicate that user released the mouse buttonshouldPaint = false;PainterForm_MouseMoveif ( shouldPaint ) // check if mouse button is being pressed{// draw a circle where the mouse pointer is presentusing ( Graphics graphics = CreateGraphics() ){graphics.FillEllipse(new SolidBrush( Color.BlueViolet ), e.X, e.Y, 4, 4 );} // end using; calls graphics.Dispose()} // end if

Chapter 6 Graphical user interface

Prepared By Namratha K

Page 164: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

164

6.7 Keyboard-Event Handling:

Key events occur when keyboard keys are pressed and released. Such events can be handled for any control that inherits from System.Windows.Forms.Control. There are three key events—KeyPress, KeyUp and KeyDown. The KeyPress event occurs when the user presses a key that represents an ASCII character. The specific key can be determined with property KeyChar of the event handler’s KeyPressEventArgs argument. ASCII is a 128-character set of alphanumeric symbols.

The KeyPress event does not indicate whether modifier keys (e.g., Shift, Alt and Ctrl) were pressed when a key event occurred. If this information is important, the KeyUp or Key- Down events can be used. The KeyEventArgs argument for each of these events contains information about modifier keys. Figure 14.39 lists important key event information. Several properties return values from the Keys enumeration, which provides constants that specify the various keys on a keyboard. Like the FontStyle enumeration , the Keys enumeration is represented with a set of bits, so the enumeration’s constants can be combined to indicate multiple keys pressed at the same time.

Fig 17: Keyboard events and event arguments.

Chapter 6 Graphical user interface Chapter 6 Graphical user interface

Prepared By Namratha K

Page 165: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

165

6.8 Menus:

Menus provide groups of related commands for Windows applications. Although these commands depend on the program, some—such as Open and Save—are common to many applications. Menus are an integral part of GUIs, because they organize commands without “cluttering” the GUI.

Visual C# IDE lists various commands (called menu items), plus submenus (menus within a menu). The top-level menus appear in the left portion of the figure, whereas any submenus or menu items are displayed to the right. The menu that contains a menu item is called that menu item’s parent menu. A menu item that contains a submenu is considered to be the parent of that submenu.Menus can have Alt key shortcuts (also called access shortcuts, keyboard shortcuts or hotkeys), which are accessed by pressing Alt and the underlined letter—for example, Alt F typically expands the File menu. Menu items can have shortcut keys as well (combinations of Ctrl, Shift, Alt, F1, F2, letter keys, and so on). Some menu items display checkmarks, usually indicating that multiple options on the menu can be selected at once.

6.9 MonthCalendar Control:

Many applications must perform date and time calculations. The .NET Framework provides two controls that allow an application to retrieve date and time information—the MonthCalendar and DateTimePicker controls.The MonthCalendar control displays a monthly calendar on the Form. Theuser can select a date from the currently displayed month or can use the provided arrows to navigate to another month. When a date is selected, it is highlighted. Multiple dates can be selected by clicking dates on the calendar while holding down the Shift key. The default event for this control is the DateChanged event, which is generated when a new date is selected. Properties are provided that allow you to modify the appearance of the calendar, how many dates can be selected at once, and the minimum date and maximum date that may be selected. MonthCalendar properties and a common MonthCalendar event are summarizedin Fig. 18

Fig 18: MonthCalendar properties and an event.

Prepared By Namratha K

Page 166: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

166

6.10 DateTimePicker Control:

The DateTimePicker control is similar to the MonthCalendar control but displays the calendar when a down arrow is selected. The DateTimePicker can be used to retrieve date and time information from the user. A DateTimePicker’s Valueproperty stores a DateTime object, which always contains both date and time information.

You can retrieve the date information from the DateTime object by using property Date, and you can retrieve only the time information by using the TimeOfDay property. The DateTimePicker is also more customizable than a MonthCalendar control more properties are provided to edit the look and feel of the

drop-down calendar. Property Format specifies the user’s selection options using the DateTimePickerFormat enumeration. The values in this enumeration are Long (displays the date in long format, as in Thursday, July 10, 2010), Short (displays the date in short format, as in 7/10/2010), Time (displays a time value, as in 5:31:02 PM) and Custom (indicates that a custom format will be used). If value Custom is used, the display in the DateTimePicker is specified using property CustomFormat. The default event for this control is ValueChanged, which occurs when the selected value (whether a date or a time) is changed. DateTimePicker properties and a common event are summarized in Fig. 19

Fig 19: DateTimePicker properties and an event.Chapter 6 Graphical user interface

Prepared By Namratha K

Page 167: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

167

6.11 LinkLabel Control:

The LinkLabel control displays links to other resources, such as files or web pagesA LinkLabel appears as underlined text (colored blue by default). When themouse moves over the link, the pointer changes to a hand; this is similar to the behavior of a hyperlink in a web page. The link can change color to indicate whether it is not yet visited, previously visited or active. When clicked, the LinkLabel generates a LinkClicked event . Class LinkLabel is derived from class Label and therefore inherits all of class Label’s functionality.

Chapter 6 Graphical user interface

Fig 20: LinkLabel properties and an event.

6.12 ListBox Control:

The ListBox control allows the user to view and select from multiple items in a list. ListBoxes are static GUI entities, which means that users cannot directly edit the list of items. The user can be provided with TextBoxes and Buttons with which to specify items to be added to the list, but the actual additions must be performed in code. The CheckedListBox control extends a ListBox by including CheckBoxes next to each item in the list. This allows users to place checks on multiple items at once, as is possible with CheckBox controls. . In both controls, scrollbars appear if the number of items exceeds the ListBox’s viewable area.

Chapter 6 Graphical user interface

Prepared By Namratha K

Page 168: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

168

Fig 21: ListBox properties, methods and an event.

6.13 CheckedListBox:

Common properties are listed below:

Chapter 6 Graphical user interface

Prepared By Namratha K

Page 169: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

169

Fig 22: CheckedListBox properties

ComboBox Control:The ComboBox control combines TextBox features with a drop-down list—a GUI component that contains a list from which a value can be selected. A ComboBox usually appears as a TextBox with a down arrow to its right. By default, the user can enter text into the TextBox or click the down arrow to display a list of predefined items. If a user chooses an element from this list, that element is displayed in the TextBox. If the list contains more elements than can be displayed in the drop-down list, a scrollbar appears. The maximum number of items that a drop-down list can display at one time is set by property MaxDrop-DownItems.

6.14 TreeView Control:The TreeView control displays nodes hierarchically in a tree. Traditionally, nodes are objects that contain values and can refer to other nodes. A parent node contains child nodes, and the child nodes can be parents to other nodes. Two child nodes that have the same parent node are considered sibling nodes. A tree is a collection of nodes, usually organized in a hierarchical manner. The first parent node of a tree is the root node (a TreeView can have multiple roots). For example, the file system of a computer can be represented as a tree. The top-level directory (perhaps C:) would be the root, each subfolder of C: would be a child node and each child folder could have its own children. TreeView controls are useful for displaying hierarchical informationChapter 6 Graphical user interface

Prepared By Namratha K

Page 170: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

170

Assignment:

1. List out any six properties and their purpose of TextBox.2. What is the purpose of using GroupBox and panels? List out their properties.3. Explain how to handle mouse events with example.4. Illustrate working with checkbox, RadioButton and GroupBox controls with a windows forms

application example.5. Write a short note on the following : i) MDI windows ii) Event driven GUI.6. Create a class called student which contains, USN, student Name and also total marks obtained. Also

overload comparison operators for comparing two students based upon their total marks obtained.

Prepared By Namratha K

Page 171: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

171

Chapter 7 Data Access with ADO.NET

Data Access with ADO .NET

7.1 Introduction

An application can have many kinds of data sources such as a simple text file, an XML file, and a database. Databases are typically used when storing different kinds of data such as the name, address, age, gender, and occupation of a person, music, pictures, and many more. A database is a collection of different kinds of data structured into tables consisting of fields and records. Most real world applications today uses databases to store information.

Relational databases contain data which are organized and linked to each other. Relational databases contain one or more tables interconnected to each other. Tables consists of rows and columns. In a database, the rows represent each record.

Structured Query Language (SQL) is the most popular and perhaps the standard way of communicating to a database. It has commands you can use for retrieving, updating, adding, and deleting data from the database. It also allows you to create and modify databases and tables and create relationships between different tables.

Database Management Systems (DBMS) such as Microsoft SQL Server allows you to quickly access data from a database. It contains different tools such as tools for querying, creating, deleting and updating a database. Most DBMS provides you a graphical interface for creating common tasks. Other examples of DBMS are Access, Oracle, and MySQL.

ADO.NET is part of the .NET framework technology that allows you to access and modify data from different data sources. It supports many types of data sources such as Microsoft SQL Server, MySQL, Oracle, and Microsoft Access. The .NET Framework provides a number of data providers that you can use. These data providers are used to connect to a data source, executes commands, and retrieve results.The following lessons uses Windows Forms Applications as a project type for connecting to databases although you can easily incorporate what you will learn in other areas such as ASP.NET.

7.2 Understanding Databases:

A database is a collection of different kinds of data structured into tables consisting of fields and records. Most real world applications today uses databases to store information.

Prepared By Namratha K

Page 172: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

172

Chapter 7 Data Access with ADO.NET

Let’s learn basics of SQL in the following statements:

Table 7.1: Lists of Basics SQL

STATEMENTS DESCRIPTION AND SYNTAX

CREATE You can create a database.

Syntax: CREATE DATABASE <Name of Database>;

Example: CREATE DATABASE MyDatabase;

You can create a table

Syntax: CREATE TABLE <Name of Table> (

<Column1> <Datatype>,

<Column2> <Datatype>,

. . .

<ColumnN> <Datatype> );

DROP

You can to remove a table, user or even an entire database.

Syntax: DROP TABLE <Name of TABLE>;

Example: DROP TABLE Employee;

INSERT

You can insert record into a table

Syntax: INSERT INTO <Table Name> VALUES (<Value1>,

Example:

Value2>, ... , <ValueN>);

INSERT INTO Employees VALUES (1, 'John', 'Smith', 21);

INSERT INTO Employees (FirstName, LastName) VALUES ('John',

'Smith');

DELETE Used to delete the records from a table.

Syntax: DELETE FROM <Table Name> WHERE

Prepared By Namratha K

Page 173: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

173

<Condition>;

Example:

DELETE FROM Employees WHERE EmployeeID = 1;

UPDATE Used to change a value of a field or fields of an existing record.

Syntax:

UPDATE <Table Name> SET <Column> = <Value> WHERE

<Condition>;

Example:

i.UPDATE Employees SET FirstName = 'Marco' WHERE

EmployeedID = 2;

ii.UPDATE Employees SET FirstName = 'Marco', LastName =

'Miller' WHERE EmployeedID = 2;

SELECT Used to get fields from a table.

Syntax:

i.SELECT * FROM <Table Name>;

ii.SELECT <Column1>, <Column2>, ... <ColumnN>

Example:

FROM <TableName>;

SELECT FirstName FROM Employees;

WHERE clauseUsed to specify a condition that you want to read selected data in the

table.

The following operators can be used in the WHERE clause:

< (less than) <= (less than or equal to) BETWEEN IN

> (greater than)

>= (greater than or equal to) LIKE

Prepared By Namratha K

Page 174: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

174

Before you deal with accessing and modifying databases, you first need to know the basics of SQL (Structured Query Language). This is the language used for querying databases. SQL is simple and easy to understand. SQL is not only used for querying data, it can pretty much do anything from creating, updating, and deleting databases and tables.

Chapter 7 Data Access with ADO.NET

STATEMENTS DESCRIPTION AND SYNTAX

LIKE clauseAllows you to use the partial string that you can specify with wildcards.

Example: SELECT * FROM customer WHERE city LIKE ‘Lo%’;

The following are the 3 possible combinations for using the wild

characters.

Lo% – Returns all the items starting with Lo, such as London, Los

Angeles.

%Lo – Returns all the items ending with Lo, such as Sao Paulo

%Lo% – Returns all the items containing Lo anywhere in the field

value, such as Barcelona,

DISTINCT

Used to avoid repetition (duplicate values in the fields of a table).

Clause Example: SELECT DISTINCT city FROM customers

You can order the records in the DataSet by using an SQL statement.

Prepared By Namratha K

Page 175: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

175

ORDER BYExample: SELECT *FROM customer ORDER BY customerid

ClauseUsed to group some records in descending order using the Desc keyword.

Example: SELECT * FROM customers ORDER BY customerid Desc

Used to group some records according to the fields of the table.

GROUP BY Example: SELECT customerid, customername FROM customers GROUP

ClauseBY customerid

You can join two or more tables in a database with SQL.

Joining TableExample: SELECT c.cname, o.oid FROM customer c , order o WHERE

c.oid=o.oid AND c.cname=“xxx”;

7.3 Understanding ADO.NET:

ADO.NET is the data access and manipulation protocol used by C#, which is used to work with data that is stored in structured data sources, such as databases and XML files. The following are some of the important topographies of ADO.NET:

Contains a number of classes that provide you with various methods and attributes to manage the communication between your application and data source.

Provides a rich set of features, such as connection and commands that can be used to develop robust and highly efficient data services in .NET applications.

Provides various data providers that are specific to databases produced by various vendors. For example, ADO.NET has a separate provider to access data from Oracle databases; whereas, another provider is used to access data from SQL databases.

Enables you to access different data sources, such as Microsoft SQL Server, and XML, as per your requirements.

Some of the important features of ADO.NET are as follows:

Prepared By Namratha K

Page 176: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

176

LINQ:

Stands for Language Integrated Query Integrated into various aspects of data access in a .NET framework which includes Dataset disconnected programming model and the existing SQL Server database schemas.

LINQ to ADO.NET consist of two separate technologies that are

LINQ to DataSet: provides better querying over DataSet.

LINQ to SQL: enables you to directly query SQL Server databases.

LINQ to DataSet:

Allows you to implement LINQ queries for disconnected data stored in a dataSet. LINQ to DataSet enables you to query data that is cached in a DataSet object. DataSet objects allow you to use a copy of the data stored in the tables of a database, without actually getting connected to the database.

Chapter 7 Data Access with ADO.NET

LINQ to SQL:Allows you to create queries for data stored in SQL server database in your .NET application. You can use the LINQ to SQL technology to translate a query into a SQL query and then use it to retrieve or manipulate data contained in tables of an SQL Server database. LINQ to SQL supports all the key functions that you like to perform while working with SQL, that is, you can insert, update, and delete information from a table.The following are list of common ADO.NET objects:

Table 7.2: Lists of Common ADO.NET objects

OBJECTS DESCRIPTION

Connection

Provides a connection to the data source to read and write data with the

help of OleDbConnection, OdbcConnection, OracleConnection

object

or SqlConnection

DataAdapter

Provides communication between a data source and a Dataset.

OleDbDataAdapter, OdbcDataAdapter, OracleDataAdapter,

object

Prepared By Namratha K

Page 177: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

177

AccessDataAdapter or SqlDataAdapter

Allows DataAdapters to read, add, update and delete the records in a data

source. DataAdapter support four properties that give you access to

Command

these command objects:-

SelectCommand

Object InsertCommand

UpdatedCommand

DeleteCommand

DataSet object

Stores data in cache that is disconnected from the data source. It allows you

to access the data in the form of tables, rows, and columns;

Holds a data table from a data source. Data tables contain two important

properties:-

DataTable Columns: which is a collection of the DataColumn objects that

object represents the columns of data in a table Rows: which is a collection of the DataRow objects that represents

the rows of data in a table

OBJECTS DESCRIPTION

Data Reader

Holds a read-only, forward-only set of data from a database. Using a data

reader can increase speed because only one row of data is in Object

Prepared By Namratha K

Page 178: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

178

at a time.

Data View Object

Represents a customized view of a single table that can be filtered,

searched, or sorted.

Checks the data integrity with the support of DataSet.

A Constraint class will refer when the rows are inserted, updated,

deleted

Three types:

Constraint object

Unique-Constraints: Which checks that the new values in a

column are unique throughout the table Foreign-key constraints: Which specify how related records

should be updated when a record in another table is updated.

Primary-key constraints: Which work similar to the unique

constraints but it does not allow the null values.

DataRelationSpecifies a relationship between parent and child tables based on a key

Object that both tables share.

DataRow object

Corresponds to a particular row in a data table. Use the Item property to

get or set a value in a particular field in the row

DataColumn

Corresponds to the columns in a table. Each object has a DataType

property that specifies the kind of data each column contains, such as

objectintegers or string values.

Prepared By Namratha K

Page 179: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

179

7.4 Describing the architecture of ADO.NET:

ADO.NET provides a bridge between the front end controls and the back end database. The ADO.NET objects encapsulate all the data access operations and the controls interact with these objects to display data, thus hiding the details of movement of data.

ADO.NET uses some ADO objects, such as the Connection and Command objects, and also introduces new objects. Key new ADO.NET objects include the DataSet, DataReader, and DataAdapter.

The following sections will introduce you to some objects that have evolved, and some that are new.

Connections - For connection to and managing transactions against a database.

Commands - For issuing SQL commands against a database.

DataReaders - For reading a forward-only stream of data records from a SQL Server data source.

DataSets - For storing, remoting and programming against flat data, XML data and relational data.

DataAdapters - For pushing data into a DataSet, and reconciling data against a database.

Chapter 7 Data Access with ADO.NET

Prepared By Namratha K

Page 180: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

180

Figure 7.1: Showing the ADO.NET Architecture

7.5 Data Provider in ADO.NET

A data provider is a set of related components that work together to provide data in an efficient manner. It is used in ADO.NET for connecting to a database, executing commands, and retrieving results. The results are either processed directly or manipulated between tiers and displayed after combining with multiple sources. The data provider increase performance without compromising on functionality.

Objects of Data Provider:

The Data provider in ADO.NET consists of the following 4 objects:

Chapter 7 Data Access with ADO.NET

Table 7.3: List of objects of Data Provider

OBJECT DESCRIPTION

• Creates connection to the data source.

• The base class for all the Connection objects is the DbConnection class.

• The Connection object has the methods for opening and closing connection and

Connectionbeginning a transaction.

Provides three types of connection classes:

• SqlConnection object: to connect to Microsoft SQL Server

• OleDbConnection object: to connect to Microsoft Access

• OdbcConnection object: to connect to Oracle

Prepared By Namratha K

Page 181: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

181

•Executes a command against the data source and retrieve a DataReader or

DataSet.

Command •It also executes the INSERT, UPDATE or DELETE command against the data

source.

• The base class for all the Command objects is the DbCommand class.

The Command object is represented by 3 classes: SqlCommand OleDbCommand OdbcCommand

Command

The Command object provides 3 methods that are used to execute commands on

the database.

ExecuteNonQuery(): method executes the commands, such as INSERT, UPDATE and DELET that have no return value.

ExecuteScalar(): method returns a single value from a database query.

ExecuteReader(): returns a result set by way of the DataReader object.

• Provides a forward-only and read-only connected result set.

DataReader•The base class for all DataReader object is the DataReader class.

• The DataReader object cannot be directly instantiated.

• Updates the DataSet with data from the data source.

• The base class for all DataAdapter objects is the DbDataAdapter class.

• The DataAdapter acts as an intermediary for all the communication between the database and DataSet.

Prepared By Namratha K

Page 182: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

182

The DataAdapter object provides 2 methods

DataAdapter Fill(): is used to fill a DataTable or DataSet with data from the database Update(): commits the changes to the database.

The DataAdapter provides 4 properties that represent the database command:

SelectCommand

InsertCommand

DeleteCommand

UpdateCommand

7.6 Data Provider in ADO.NET:

Different types of data providers include in ADO.NET are as follows:

Table 7.4 List of different types of data provider

DataDescription

provider

• Provides access to Microsoft SQL.

•It uses the System.Data.SqlClient namespace and its own protocol to

SQL communicate with the SQL Server.

Server • It performs well when used to access a SQL Server.

•There is no need to add an OLEDB or the ODBC layer to access the data

provider.

• Provides access to data sources exposed by using OLEDB.

OLEDB • It uses the System.Data.OleDb namespace and holds support for both local and distributed transaction.

Prepared By Namratha K

Page 183: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

183

• Provides access to data sources exposed by using ODBC.

ODBC • It uses the System.Data.Odbc namespace and holds support for both local and distributed transaction.

• Provides access to Oracle data source Oracle client connectivity software. Oracle • It uses the System.Data.Oracledlient namespace and is contained in the

System.Data.OracleClient.dll assembly

7.7 DataSet:

DataSet is a very useful in-memory representation of data and acts as the core of a wide variety of the data based applications. A DataSet can be considered as a local copy of the relevant portions of the database. The data in the DataSet can be manipulated and updated independent of the database. You can load the data in the DataSet from any valid source, such as the MicrosoftSQLServer database, Oracle Database, or Microsoft Access database.

Component of DataSets:

The various components that make up a DataSet are listed as follow:

Chapter 7 Data Access with ADO.NET

Table 7.5: List of various components of DataSet

DataSetDescription

Components

Consists of DataRow and DataColumn and stores data in the table row

format.

DataTable The DataTable is the central object of the ADO.NET library and similar to a

Prepared By Namratha K

Page 184: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

184

table in a database.

The maximum number of rows that a DataTable can contain is fixed at

16,777,216.

Represents a customized view of DataTable for sorting, filtering, searching,

editing and navigation.

DataView A DataView allows you to create a view on a DataTable to see a subset of

data based on a preset condition specified in the RowStateFilter property.

A Dataview can be used to present a subset of data from the DataTable.

Consists of a number of columns that comprise a DataTable.

DataColumn A DataColumn is the essential building block of the DataTable.

A DataType property of DataColumn determines the kind of data that a

column holds.

Represents a row in the DataTable.

You can use the DataRow object and its properties and methods to retrieve, evaluate, insert, delete and update the values in the DataTable.

DataRow You can use NewRow() method of the DataTable to create a new DataRow and the Add() method to add the new DataRow to the

DataTable.

You can also delete DataRow using Remove() method.

Chapter 7 Data Access with ADO.NET

Allows you to specify relations between various tables.

Prepared By Namratha K

Page 185: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

185

In simple words, a DataRelation is used to relate two DataTable objects

DataRelationto each other through DataColumn objects.

The relationships are created between matching columns in the parent and child tables.

7.8 DataReader:

The DataReader object helps in retrieving the data from a database in a forward-only, read-only mode. The base class for all the DataReader objects is the DbDataReader class.

The DataReader object is returned as a result of calling the ExecuteReader() method of the Command object. The DataReader object enables faster retrieval of data from databases and enhances the performance of .NET applications by providing rapid data access speed. However, it is less preferred as compared to the DataAdapter object because the DataReader object needs an Open connection till it completes reading all the rows of the specified table.

An Open connection to read data from large tables consumes most of the system resources. When multiple client applications simultaneously access a database by using the DataReader object, the performance of data retrieval and other related processes is substantially reduced. In such a case, the database might refuse connections to other .NET applications until other clients free the resources.

7.9 ADO.NET Entity Framework

ADO.NET Entity Framework 4.0 is introduced in .NET Framework 4.0 and includes the following components:

EDM (Entity Data Model): EDM consists of three main parts - Conceptual model, Mapping and Storage model.

Conceptual Model: The conceptual model contains the model classes and their relationships. This will be independent from your database table design.

Storage Model: Storage model is the database design model which includes tables, views, stored procedures, and their relationships and keys.

Mapping: Mapping consists of information about how the conceptual model is mapped to the storage model.

Chapter 7 Data Access with ADO.NET

Prepared By Namratha K

Page 186: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

186

LINQ to Entities: LINQ to Entities is a query language used to write queries against the object model. It returns entities, which are defined in the conceptual model. You can use your LINQ skills here.

Entity SQL: Entity SQL is another query language just like LINQ to Entities. However, it is a little more difficult than L2E and the developer will have to learn it separately.

Object Service:Object service is a main entry point for accessing data from the database and to return it back. Object service is responsible for materialization, which is the process of converting data returned from an entity client data provider (next layer) to an entity object structure.

Entity Client Data Provider: The main responsibility of this layer is to convert L2E or Entity SQL queries into a SQL query which is understood by the underlying database. It communicates with the ADO.Net data provider which in turn sends or retrieves data from the database.

EDM

Figure 7.2: Showing the Architecture of Entity Framework

Chapter 7 Data Access with ADO.NET

Prepared By Namratha K

Page 187: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

187

7.10 Creating Connection String:

A connection string is a series of name/value pairs separated by semicolon that indicate the settings for connecting to a database. Such settings include the location of the database, authentication, security, and the name of the database to connect to. Connection strings for different data sources are not exactly the same.

For example: OLE DB and ODBC requires an OLE DB and ODBC driver to be specified in their connection strings.

The Connection classes of the data providers provide a ConnectionString property that you can use to specify the connection string for connecting to a database. Here is an example of a connection string for connecting to a SQL Server Express data source:

Data Source=.\SQLEXPRESS;Initial Catalog=University; Integrated Security=SSPI;

The following table is the basic connection string parameters that you can use when building your connection string.

Note that not all parameters are the same for every data source.

Table 7.6: Lists of basic connection string parameters

Parameter Description

AttachDBFileName

Used only if you want to connect to an attachable database file.

For example, an .mdf file that isn't registered with the database system.

/ InitialFileName The full version of SQL Server doesn't support this.

Connect Timeout /

The length of time (in seconds) to wait for a connection to the server

before terminating the attempt and generating an error.

Connection Timeout

Defaults to 15 seconds and 0 seconds represent an infinite wait.

Data Source / The server name or network address of the database product to

Prepared By Namratha K

Page 188: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

188

Server / Address /connect to.

Add / Network Use localhost for the current computer.

Address

Initial Catalog /The database the connection will initially use.

Database

Integrated Security /

Defaults to false. When set to true or SSPI, the .NET provider attempts

Trusted_Connection

to connect to the data source using Windows integrated security.

When set to false (the default), security-sensitive information such as

Persist Security Info

the password is removed from the ConnectionString property as soon as

the connection is opened. Thus, you can't retrieve this information in

your code.

User ID The database account user ID.

Password/Pwd The password corresponding to the User ID.

7.11 Working with DataAdapters:

A DataAdapters are a set of objects used to exchange data between a data source and DataSet. This means that DataAdapter is responsible for reading data from a database into a DataSet and writing the changed data from the DatSet to the database. The available DataAdapters in a .NET framework are as follows:

Table 7.7: List of DataAdapter class for different providers in .NET

Prepared By Namratha K

Page 189: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

189

ProviderDataAdapter Class Description

SQL Server SqlDataAdapter Works only with SQL Server

OLE DB OleDbDataAdapter

Allows you to work with any data source exposed by

the OLE DB provider.

ODBC OdbcDataAdapter Allow you to access on ODBC data source

ORACLE OracleDataAdapter Works with Oracle database

The DbDataAdapter class provides the following properties and methods.

Table 7.8: List of properties in DataAdapter class

Property Description

DeleteCommand

Speicfies the Command object with the SQL command to be used for

deleting a record.

FillCommandBehavior

Specifies the behavior of the command used to fill the data adapter.

InsertCommand

Specifies the Command object with the SQL command used for

inserting a record.

SelectCommand

Specifies the Command object with the SQL command to be used for

retrieving records.

Prepared By Namratha K

Page 190: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

190

UpdateBatchSizeSpecifies the number of commands that can be executed as a batch.

UpdateCommand

Specifies the Command object with the SQL command to be used for

updating a record.

Chapter 7 Data Access with ADO.NET

Table 7.9: List of methods in DataAdapter class

Methods Description

AddToBatch Adds a Command object to a batch that will be executed.

ClearBatch Removes all the Command objects from the batch.

ExecuteBatch Excutes the batch of commands.

Fill

Executes the SelectCommand property and fills a DataSet that is

provided.

InitializeBatching Initialize the batching process.

GetFillParameters Gets the parameters of the SelectCommand property.

Prepared By Namratha K

Page 191: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

191

TerminateBatching Terminates the batching process.

Calls the corresponding INSERT, DELETE, or UPDATE command of

Updatethis DataAdapter and updates the data source using the specified

commands.

Chapter 7 Data Access with ADO.NET

7.12 Using DataReader: A DataReader object allows forward-only, read-only access to a database. Using DataReader is the connected way of accessing data and an open connection must be available first. Each provider has its own version of DataReader which inherits the System.Data.Common.DbDataReader base class.You can retrieve the data in windows application by using DataReader instead of DataAdapter. You can use the ExecuteReader() to retrieve the rows from a data source. There are different DataReader for different data source.Table 7.7: List of DataReader class for different providers in .NET

ProviderDataReader Class Description

SQL Server SqlDataReader Works only with SQL Server

OLE DB OleDbDataReader

Allows you to work with any data source exposed by

the OLE DB provider.

ODBC OdbcDataReader Allow you to access on ODBC data source

ORACLE OracleDataReader Works with Oracle database

The DbDataReader class contains properties and methods used for reading a row in a database table. Some of this are presented in the following tables.

Table 7.8: List of properties in DataReader class

Prepared By Namratha K

Page 192: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

192

Property Description

FieldCount Specifies the number of columns of the current row or record.

HasRows Specifies whether the current row has at least 1 row.

IsClosed Specifies whether the DbDataReader is closed.

RecordsAffected

Specifies the number of rows that has been updated, inserted, or

deleted.

Table 7.9: List of methods in DataAdapter class

Methods Description

GetBoolean Gets the value of a column as a boolean value.

GetChar Gets the value of a column as a char value.

GetDataTypeName Gets the name of the data type of the current column.

GetDateTime Gets the value of the column as a DateTime object.

GetDecimal Gets the value of the column as a decimal value.

GetDouble Gets the value of the column as a double value.

GetFieldType Gets the field type of the specified column.

GetInt32 Gets the value of the column as an int value.

Prepared By Namratha K

Page 193: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

193

GetName Gets the name of the column.

GetOrdinal Gets the column ordinal with the specified column name.

GetString Gets the value of the column as a string value.

GetValue Gets the value of a column as an object.

GetValues Gets all the column of a row as an array of objects.

NextResult

Advances the reader to the next result when reading the

results of a batch of statements.

Read Advances the reader to the next record.

Prepared By Namratha K

Page 194: namrathakalasannavar955210856.files.wordpress.com.…  · Web view.NET Framework is an essential component of the Windows operating system, which helps in creating applications by

194

Prepared By Namratha K