1. How to store Grid values to database,get, display(insert,update,delete, cancel,find)?
2. Sessions, Type of session, how to use sessions?
3. cookies , type of cookies , user cookies, fetch cookies values.
4. Cursors? why we use cursors?
5. Triggers and user triggers?
6. indexes ?type of indexes and why we use nd how to use indexes?
7. State Management nd type of statement mgmt.?
8. wat is view state nd how we use?
9. interfaces nd how can use use?
10. CSS nd how to use?
11. validation nd type of validation
12. wat is scripting language ?
13. use of java script?
14. if else looping in database queries?
15. COM nd its attributes?
16. How file nd image uploaed into database?
17. abstract classes?
18. CLR?
19. diff b//t CLR nd CLS?
20. DLL?
21. Assesmbly?
22. Managed code?
23. diff between storeprocedure nd functions?
24. constraints(Primary key, Foreign key, Candidate key
25. join nd its types
26. queries string? how can we use?
27. diff bet server.transfer nd response.redirect?
28. diff. between datagrid nd gridview?
29. diff in dataaset nd dataview?
30. how can we add new table in dataset at runtime?
31. diff in data adapter nd datareader?
32. Page lifecycle?
Saturday, July 30, 2011
50 New Features of SQL Server 2008
50 New Features of SQL Server 2008
Transparent Data Encryption
Enable encryption of an entire database, data files, or log files, without the need for application changes. Benefits of this include: Search encrypted data using both range and fuzzy searches, search secure data from unauthorized users, and data encryption without any required changes in existing applications.
Extensible Key Management
SQL Server 2005 provides a comprehensive solution for encryption and key management. SQL Server 2008 delivers an excellent solution to this growing need by supporting third-party key management and HSM products.
Auditing
Create and manage auditing via DDL, while simplifying compliance by providing more comprehensive data auditing. This enables organizations to answer common questions, such as, "What data was retrieved?"
Enhanced Database Mirroring
SQL Server 2008 builds on SQL Server 2005 by providing a more reliable platform that has enhanced database mirroring, including automatic page repair, improved performance, and enhanced supportability.
Automatic Recovery of Data Pages
SQL Server 2008 enables the principal and mirror machines to transparently recover from 823/824 types of data page errors by requesting a fresh copy of the suspect page from the mirroring partner transparently to end users and applications.
Log Stream Compression
Database mirroring requires data transmissions between the participants of the mirroring implementations. With SQL Server 2008, compression of the outgoing log stream between the participants delivers optimal performance and minimizes the network bandwidth used by database mirroring.
Resource Governor
Provide a consistent and predictable response to end users with the introduction of Resource Governor, allowing organizations to define resource limits and priorities for different workloads, which enable concurrent workloads to provide consistent performance to their end users.
Predictable Query Performance
Enable greater query performance stability and predictability by providing functionality to lock down query plans, enabling organizations to promote stable query plans across hardware server replacements, server upgrades, and production deployments.
Data Compression
Enable data to be stored more effectively, and reduce the storage requirements for your data. Data compression also provides significant performance improvements for large I/O bound workloads, like data warehousing.
Hot Add CPU
Dynamically scale a database on demand by allowing CPU resources to be added to SQL Server 2008 on supported hardware platforms without forcing any downtime on applications. Note that SQL Server already supports the ability to add memory resources online.
Policy-Based Management
Policy-Based Management is a policy-based system for managing one or more instances of SQL Server 2008. Use this with SQL Server Management Studio to create policies that manage entities on the server, such as the instance of SQL Server, databases, and other SQL Server objects.
Streamlined Installation
SQL Server 2008 introduces significant improvements to the service life cycle for SQL Server through the re-engineering of the installation, setup, and configuration architecture. These improvements separate the installation of the physical bits on the hardware from the configuration of the SQL Server software, enabling organizations and software partners to provide recommended installation configurations.
Performance Data Collection
Performance tuning and troubleshooting are time-consuming tasks for the administrator. To provide actionable performance insights to administrators, SQL Server 2008 includes more extensive performance data collection, a new centralized data repository for storing performance data, and new tools for reporting and monitoring.
Language Integrated Query (LINQ)
Enable developers to issue queries against data, using a managed programming language, such as C# or VB.NET, instead of SQL statements. Enable seamless, strongly typed, set-oriented queries written in .NET languages to run against ADO.NET (LINQ to SQL), ADO.NET DataSets (LINQ to DataSets), the ADO.NET Entity Framework (LINQ to Entities), and to the Entity Data Service Mapping provider. Use the new LINQ to SQL provider that enables developers to use LINQ directly on SQL Server 2008 tables and columns.
ADO.NET Data Services
The Object Services layer of ADO.NET enables the materialization, change tracking, and persistence of data as CLR objects. Developers using the ADO.NET framework can program against a database, using CLR objects that are managed by ADO.NET. SQL Server 2008 introduces more efficient, optimized support that improves performance and simplifies development.
DATE/TIME
SQL Server 2008 introduces new date and time data types:
DATE—A date-only type
TIME—A time-only type
DATETIMEOFFSET—A time-zone-aware datetime type
DATETIME2—A datetime type with larger fractional seconds and year range than the existing DATETIME type
The new data types enable applications to have separate data and time types while providing large data ranges or user defined precision for time values.
HIERARCHY ID
Enable database applications to model tree structures in a more efficient way than currently possible. New system type HierarchyId can store values that represent nodes in a hierarchy tree. This new type will be implemented as a CLR UDT, and will expose several efficient and useful built-in methods for creating and operating on hierarchy nodes with a flexible programming model.
FILESTREAM Data
Allow large binary data to be stored directly in an NTFS file system, while preserving an integral part of the database and maintaining transactional consistency. Enable the scale-out of large binary data traditionally managed by the database to be stored outside the database on more cost-effective storage without compromise.
Integrated Full Text Search
Integrated Full Text Search makes the transition between Text Search and relational data seamless, while enabling users to use the Text Indexes to perform high-speed text searches on large text columns.
Sparse Columns
NULL data consumes no physical space, providing a highly efficient way of managing empty data in a database. For example, Sparse Columns allows object models that typically have numerous null values to be stored in a SQL Server 2005 database without experiencing large space costs.
Large User-Defined Types
SQL Server 2008 eliminates the 8-KB limit for User-Defined Types (UDTs), allowing users to dramatically expand the size of their UDTs.
Spatial Data Types
Build spatial capabilities into your applications by using the support for spatial data.
Implement Round Earth solutions with the geography data type. Use latitude and longitude coordinates to define areas on the Earth's surface.
Implement Flat Earth solutions with the geometry data type. Store polygons, points, and lines that are associated with projected planar surfaces and naturally planar data, such as interior spaces.
Backup Compression
Keeping disk-based backups online is expensive and time-consuming. With SQL Server 2008 backup compression, less storage is required to keep backups online, and backups run significantly faster since less disk I/O is required.
Partitioned Table Parallelism
Partitions enable organizations to manage large growing tables more effectively by transparently breaking them into manageable blocks of data. SQL Server 2008 builds on the advances of partitioning in SQL Server 2005 by improving the performance on large partitioned tables.
Star Join Query Optimizations
SQL Server 2008 provides improved query performance for common data warehouse scenarios. Star Join Query optimizations reduce query response time by recognizing data warehouse join patterns.
Grouping Sets
Grouping Sets is an extension to the GROUP BY clause that lets users define multiple groupings in the same query. Grouping Sets produces a single result set that is equivalent to a UNION ALL of differently grouped rows, making aggregation querying and reporting easier and faster.
Change Data Capture
With Change Data Capture, changes are captured and placed in change tables. It captures complete content of changes, maintains cross-table consistency, and even works across schema changes. This enables organizations to integrate the latest information into the data warehouse.
MERGE SQL Statement
With the introduction of the MERGE SQL Statement, developers can more effectively handle common data warehousing scenarios, like checking whether a row exists, and then executing an insert or update.
SQL Server Integration Services (SSIS) Pipeline Improvements
Data Integration packages can now scale more effectively, making use of available resources and managing the largest enterprise-scale workloads. The new design improves the scalability of runtime into multiple processors.
SQL Server Integration Services (SSIS) Persistent Lookups
The need to perform lookups is one of the most common ETL operations. This is especially prevalent in data warehousing, where fact records need to use lookups to transform business keys to their corresponding surrogates. SSIS increases the performance of lookups to support the largest tables.
Analysis Scale and Performance
SQL Server 2008 drives broader analysis with enhanced analytical capabilities and with more complex computations and aggregations. New cube design tools help users streamline the development of the analysis infrastructure enabling them to build solutions for optimized performance.
Block Computations
Block Computations provides a significant improvement in processing performance enabling users to increase the depth of their hierarchies and complexity of the computations.
Writeback
New MOLAP enabled writeback capabilities in SQL Server 2008 Analysis Services removes the need to query ROLAP partitions. This provides users with enhanced writeback scenarios from within analytical applications without sacrificing the traditional OLAP performance.
Enterprise Reporting Engine
Reports can easily be delivered throughout the organization, both internally and externally, with simplified deployment and configuration. This enables users to easily create and share reports of any size and complexity.
Internet Report Deployment
Customers and suppliers can effortlessly be reached by deploying reports over the Internet.
Manage Reporting Infrastructure
Increase supportability and the ability to control server behaviour with memory management, infrastructure consolidation, and easier configuration through a centralized store and API for all configuration settings.
Report Builder Enhancements
Easily build ad-hoc and author reports with any structure through Report Designer.
Forms Authentication Support
Support for Forms authentication enables users to choose between Windows and Forms authentication.
Report Server Application Embedding
Report Server application embedding enables the URLs in reports and subscriptions to point back to front-end applications.
Microsoft Office Integration
SQL Server 2008 provides new Word rendering that enables users to consume reports directly from within Microsoft Office Word. In addition, the existing Excel renderer has been greatly enhanced to accommodate the support of features, like nested data regions, sub-reports, as well as merged cell improvements. This lets users maintain layout fidelity and improves the overall consumption of reports from Microsoft Office applications.
Predictive Analysis
SQL Server Analysis Services continues to deliver advanced data mining technologies. Better Time Series support extends forecasting capabilities. Enhanced Mining Structures deliver more flexibility to perform focused analysis through filtering as well as to deliver complete information in reports beyond the scope of the mining model. New cross-validation enables confirmation of both accuracy and stability for results that you can trust. Furthermore, the new features delivered with SQL Server 2008 Data Mining Add-ins for Office 2007 empower every user in the organization with even more actionable insight at the desktop.
Transparent Data Encryption
Enable encryption of an entire database, data files, or log files, without the need for application changes. Benefits of this include: Search encrypted data using both range and fuzzy searches, search secure data from unauthorized users, and data encryption without any required changes in existing applications.
Extensible Key Management
SQL Server 2005 provides a comprehensive solution for encryption and key management. SQL Server 2008 delivers an excellent solution to this growing need by supporting third-party key management and HSM products.
Auditing
Create and manage auditing via DDL, while simplifying compliance by providing more comprehensive data auditing. This enables organizations to answer common questions, such as, "What data was retrieved?"
Enhanced Database Mirroring
SQL Server 2008 builds on SQL Server 2005 by providing a more reliable platform that has enhanced database mirroring, including automatic page repair, improved performance, and enhanced supportability.
Automatic Recovery of Data Pages
SQL Server 2008 enables the principal and mirror machines to transparently recover from 823/824 types of data page errors by requesting a fresh copy of the suspect page from the mirroring partner transparently to end users and applications.
Log Stream Compression
Database mirroring requires data transmissions between the participants of the mirroring implementations. With SQL Server 2008, compression of the outgoing log stream between the participants delivers optimal performance and minimizes the network bandwidth used by database mirroring.
Resource Governor
Provide a consistent and predictable response to end users with the introduction of Resource Governor, allowing organizations to define resource limits and priorities for different workloads, which enable concurrent workloads to provide consistent performance to their end users.
Predictable Query Performance
Enable greater query performance stability and predictability by providing functionality to lock down query plans, enabling organizations to promote stable query plans across hardware server replacements, server upgrades, and production deployments.
Data Compression
Enable data to be stored more effectively, and reduce the storage requirements for your data. Data compression also provides significant performance improvements for large I/O bound workloads, like data warehousing.
Hot Add CPU
Dynamically scale a database on demand by allowing CPU resources to be added to SQL Server 2008 on supported hardware platforms without forcing any downtime on applications. Note that SQL Server already supports the ability to add memory resources online.
Policy-Based Management
Policy-Based Management is a policy-based system for managing one or more instances of SQL Server 2008. Use this with SQL Server Management Studio to create policies that manage entities on the server, such as the instance of SQL Server, databases, and other SQL Server objects.
Streamlined Installation
SQL Server 2008 introduces significant improvements to the service life cycle for SQL Server through the re-engineering of the installation, setup, and configuration architecture. These improvements separate the installation of the physical bits on the hardware from the configuration of the SQL Server software, enabling organizations and software partners to provide recommended installation configurations.
Performance Data Collection
Performance tuning and troubleshooting are time-consuming tasks for the administrator. To provide actionable performance insights to administrators, SQL Server 2008 includes more extensive performance data collection, a new centralized data repository for storing performance data, and new tools for reporting and monitoring.
Language Integrated Query (LINQ)
Enable developers to issue queries against data, using a managed programming language, such as C# or VB.NET, instead of SQL statements. Enable seamless, strongly typed, set-oriented queries written in .NET languages to run against ADO.NET (LINQ to SQL), ADO.NET DataSets (LINQ to DataSets), the ADO.NET Entity Framework (LINQ to Entities), and to the Entity Data Service Mapping provider. Use the new LINQ to SQL provider that enables developers to use LINQ directly on SQL Server 2008 tables and columns.
ADO.NET Data Services
The Object Services layer of ADO.NET enables the materialization, change tracking, and persistence of data as CLR objects. Developers using the ADO.NET framework can program against a database, using CLR objects that are managed by ADO.NET. SQL Server 2008 introduces more efficient, optimized support that improves performance and simplifies development.
DATE/TIME
SQL Server 2008 introduces new date and time data types:
DATE—A date-only type
TIME—A time-only type
DATETIMEOFFSET—A time-zone-aware datetime type
DATETIME2—A datetime type with larger fractional seconds and year range than the existing DATETIME type
The new data types enable applications to have separate data and time types while providing large data ranges or user defined precision for time values.
HIERARCHY ID
Enable database applications to model tree structures in a more efficient way than currently possible. New system type HierarchyId can store values that represent nodes in a hierarchy tree. This new type will be implemented as a CLR UDT, and will expose several efficient and useful built-in methods for creating and operating on hierarchy nodes with a flexible programming model.
FILESTREAM Data
Allow large binary data to be stored directly in an NTFS file system, while preserving an integral part of the database and maintaining transactional consistency. Enable the scale-out of large binary data traditionally managed by the database to be stored outside the database on more cost-effective storage without compromise.
Integrated Full Text Search
Integrated Full Text Search makes the transition between Text Search and relational data seamless, while enabling users to use the Text Indexes to perform high-speed text searches on large text columns.
Sparse Columns
NULL data consumes no physical space, providing a highly efficient way of managing empty data in a database. For example, Sparse Columns allows object models that typically have numerous null values to be stored in a SQL Server 2005 database without experiencing large space costs.
Large User-Defined Types
SQL Server 2008 eliminates the 8-KB limit for User-Defined Types (UDTs), allowing users to dramatically expand the size of their UDTs.
Spatial Data Types
Build spatial capabilities into your applications by using the support for spatial data.
Implement Round Earth solutions with the geography data type. Use latitude and longitude coordinates to define areas on the Earth's surface.
Implement Flat Earth solutions with the geometry data type. Store polygons, points, and lines that are associated with projected planar surfaces and naturally planar data, such as interior spaces.
Backup Compression
Keeping disk-based backups online is expensive and time-consuming. With SQL Server 2008 backup compression, less storage is required to keep backups online, and backups run significantly faster since less disk I/O is required.
Partitioned Table Parallelism
Partitions enable organizations to manage large growing tables more effectively by transparently breaking them into manageable blocks of data. SQL Server 2008 builds on the advances of partitioning in SQL Server 2005 by improving the performance on large partitioned tables.
Star Join Query Optimizations
SQL Server 2008 provides improved query performance for common data warehouse scenarios. Star Join Query optimizations reduce query response time by recognizing data warehouse join patterns.
Grouping Sets
Grouping Sets is an extension to the GROUP BY clause that lets users define multiple groupings in the same query. Grouping Sets produces a single result set that is equivalent to a UNION ALL of differently grouped rows, making aggregation querying and reporting easier and faster.
Change Data Capture
With Change Data Capture, changes are captured and placed in change tables. It captures complete content of changes, maintains cross-table consistency, and even works across schema changes. This enables organizations to integrate the latest information into the data warehouse.
MERGE SQL Statement
With the introduction of the MERGE SQL Statement, developers can more effectively handle common data warehousing scenarios, like checking whether a row exists, and then executing an insert or update.
SQL Server Integration Services (SSIS) Pipeline Improvements
Data Integration packages can now scale more effectively, making use of available resources and managing the largest enterprise-scale workloads. The new design improves the scalability of runtime into multiple processors.
SQL Server Integration Services (SSIS) Persistent Lookups
The need to perform lookups is one of the most common ETL operations. This is especially prevalent in data warehousing, where fact records need to use lookups to transform business keys to their corresponding surrogates. SSIS increases the performance of lookups to support the largest tables.
Analysis Scale and Performance
SQL Server 2008 drives broader analysis with enhanced analytical capabilities and with more complex computations and aggregations. New cube design tools help users streamline the development of the analysis infrastructure enabling them to build solutions for optimized performance.
Block Computations
Block Computations provides a significant improvement in processing performance enabling users to increase the depth of their hierarchies and complexity of the computations.
Writeback
New MOLAP enabled writeback capabilities in SQL Server 2008 Analysis Services removes the need to query ROLAP partitions. This provides users with enhanced writeback scenarios from within analytical applications without sacrificing the traditional OLAP performance.
Enterprise Reporting Engine
Reports can easily be delivered throughout the organization, both internally and externally, with simplified deployment and configuration. This enables users to easily create and share reports of any size and complexity.
Internet Report Deployment
Customers and suppliers can effortlessly be reached by deploying reports over the Internet.
Manage Reporting Infrastructure
Increase supportability and the ability to control server behaviour with memory management, infrastructure consolidation, and easier configuration through a centralized store and API for all configuration settings.
Report Builder Enhancements
Easily build ad-hoc and author reports with any structure through Report Designer.
Forms Authentication Support
Support for Forms authentication enables users to choose between Windows and Forms authentication.
Report Server Application Embedding
Report Server application embedding enables the URLs in reports and subscriptions to point back to front-end applications.
Microsoft Office Integration
SQL Server 2008 provides new Word rendering that enables users to consume reports directly from within Microsoft Office Word. In addition, the existing Excel renderer has been greatly enhanced to accommodate the support of features, like nested data regions, sub-reports, as well as merged cell improvements. This lets users maintain layout fidelity and improves the overall consumption of reports from Microsoft Office applications.
Predictive Analysis
SQL Server Analysis Services continues to deliver advanced data mining technologies. Better Time Series support extends forecasting capabilities. Enhanced Mining Structures deliver more flexibility to perform focused analysis through filtering as well as to deliver complete information in reports beyond the scope of the mining model. New cross-validation enables confirmation of both accuracy and stability for results that you can trust. Furthermore, the new features delivered with SQL Server 2008 Data Mining Add-ins for Office 2007 empower every user in the organization with even more actionable insight at the desktop.
IIS 7.0 New features
IIS 7.0 New features
Wondering what the new features in IIS 7.0 going to be? Here you go! you can get a glimpse of IIS 7.0 in this article.
IIS7 will ship with both Windows Vista and Windows Longhorn Server. It's obvious that Microsoft has put a lot of time and effort into this release and you can expect IIS7 to be the platform of choice as soon as people can get their servers upgraded. It includes a several new functionalities with very rich integration with ASP.NET.
Feature 1: HttpModules and HttpHandlers can participate in all the requests i.e we can have a ASP.NET HttpModule for a JSP or PHP page even. Building HTTPmodules for authentication, authorization, logging, url-rewriting, auditing now will be very easy with .NET.
Feature 2: ASP.NET configuration can be integrated with IIS. IIS now uses the same web.config configuration model, which means you can have both configure ASP.NET and IIS in a single web.config file. You can now set things like default pages, IIS security, logging, etc within a web.config file and xcopy/ftp it to a server.
Feature 3: This has an integrated Admin UI tool that can manage both IIS and ASP.NET settings. Rich GUI supports settings for Membership, Roles and Profile providers. This tool also supports remote delegated admin over http -- which means you can point the rich-client admin tool at a shared host server and manage your users/roles/profile settings remotely over http.
Feature 4: It provides better request auditing and error debugging. A new functionality called "Failed Request Event Buffering" (affectionately known as "FREB") is introduced. This allows administrators to configure applications to automatically save request information anytime an error occurs during a request, or if a request takes longer than a specified amount of time to complete. This allows us to analyze what exactly happened during a request failure and what errors or exceptions have occurred. This can capture tracing messages generated within ASP.NET or within any component or class library that uses System.Diagnostics -- which makes it much easier for developers and admins to instrument and analyze what is going on with systems at runtimes.
Feature 5: It provides better configuration APIs and command-line tools. In addition to new config and admin APIs, we now have a great command-line admin story that you can use to set/modify/retrieve all configuration information as well as manage the server (start/stop individual apps, lookup their health state, register new apps, refresh SSL certs, etc). The class hierarchy in brief can be figured as:
A code snippet uses the new .NET APIs to query IIS7 to list the active worker processes on the computer. It also lists the Requests and other details about the request like Url, Clinet IP address ..etc.
ServerManager iisManager = new ServerManager();
foreach(WorkerProcess w3wp in iisManager.WorkerProcesses)
{
Console.WriteLine("W3WP ({0})", w3wp.ProcessId);
foreach (Request request in w3wp.GetRequests(0))
{
Console.WriteLine("{0} - {1},{2},{3}",
request.Url,
request.ClientIPAddr,
request.TimeElapsed,
request.TimeInState);
}
}
Feature 7: Let us examine the new management UI. Here's what the new IIS Manager looks like:
The first thing to notice is the new "Features View" which is shown above. While you can still use the "Content View" to show the files that make up your Web Site in the main pane of the tool, most of the time you'll be using the "Features View" to change site and application settings.
Feature 8: "Actions" pane is a task-based pane shows you the most common tasks that are related to the currently selected object. For example, here's a close up of the "Actions" pane as it looks when the "Default Web Site" is the currently selected object.
The contents of the "Actions" pane will naturally change as the selected object changes, but this pane is where you'll generally find links that lead you through most of your common admin tasks.
Feature 9: Modular Architecture
Unless you've been living under a rock somewhere for the past few years, you've heard about all the problems that IIS has had when it comes to security. In earlier versions of IIS, it was either installed or it wasn't. If IIS was installed then all the features were installed. In an attempt to minimize potential vulnerability, in IIS 6, the majority of features were disabled by default, but they still got installed. This time around Microsoft has taken the next logical step. IIS7 is almost completely modular. Take a look at the installation screen:
Now granted, I've installed everything to play around with it all, but on a production server, you now have the flexibility to install only the features you need. That way if you don't use CGI, then you don't need to worry about some new bug that someone finds in the CGI handler. You also won't need to install a patch and reboot, because the affected code was never even installed on your server so there's nothing to patch
Wondering what the new features in IIS 7.0 going to be? Here you go! you can get a glimpse of IIS 7.0 in this article.
IIS7 will ship with both Windows Vista and Windows Longhorn Server. It's obvious that Microsoft has put a lot of time and effort into this release and you can expect IIS7 to be the platform of choice as soon as people can get their servers upgraded. It includes a several new functionalities with very rich integration with ASP.NET.
Feature 1: HttpModules and HttpHandlers can participate in all the requests i.e we can have a ASP.NET HttpModule for a JSP or PHP page even. Building HTTPmodules for authentication, authorization, logging, url-rewriting, auditing now will be very easy with .NET.
Feature 2: ASP.NET configuration can be integrated with IIS. IIS now uses the same web.config configuration model, which means you can have both configure ASP.NET and IIS in a single web.config file. You can now set things like default pages, IIS security, logging, etc within a web.config file and xcopy/ftp it to a server.
Feature 3: This has an integrated Admin UI tool that can manage both IIS and ASP.NET settings. Rich GUI supports settings for Membership, Roles and Profile providers. This tool also supports remote delegated admin over http -- which means you can point the rich-client admin tool at a shared host server and manage your users/roles/profile settings remotely over http.
Feature 4: It provides better request auditing and error debugging. A new functionality called "Failed Request Event Buffering" (affectionately known as "FREB") is introduced. This allows administrators to configure applications to automatically save request information anytime an error occurs during a request, or if a request takes longer than a specified amount of time to complete. This allows us to analyze what exactly happened during a request failure and what errors or exceptions have occurred. This can capture tracing messages generated within ASP.NET or within any component or class library that uses System.Diagnostics -- which makes it much easier for developers and admins to instrument and analyze what is going on with systems at runtimes.
Feature 5: It provides better configuration APIs and command-line tools. In addition to new config and admin APIs, we now have a great command-line admin story that you can use to set/modify/retrieve all configuration information as well as manage the server (start/stop individual apps, lookup their health state, register new apps, refresh SSL certs, etc). The class hierarchy in brief can be figured as:
A code snippet uses the new .NET APIs to query IIS7 to list the active worker processes on the computer. It also lists the Requests and other details about the request like Url, Clinet IP address ..etc.
ServerManager iisManager = new ServerManager();
foreach(WorkerProcess w3wp in iisManager.WorkerProcesses)
{
Console.WriteLine("W3WP ({0})", w3wp.ProcessId);
foreach (Request request in w3wp.GetRequests(0))
{
Console.WriteLine("{0} - {1},{2},{3}",
request.Url,
request.ClientIPAddr,
request.TimeElapsed,
request.TimeInState);
}
}
Feature 7: Let us examine the new management UI. Here's what the new IIS Manager looks like:
The first thing to notice is the new "Features View" which is shown above. While you can still use the "Content View" to show the files that make up your Web Site in the main pane of the tool, most of the time you'll be using the "Features View" to change site and application settings.
Feature 8: "Actions" pane is a task-based pane shows you the most common tasks that are related to the currently selected object. For example, here's a close up of the "Actions" pane as it looks when the "Default Web Site" is the currently selected object.
The contents of the "Actions" pane will naturally change as the selected object changes, but this pane is where you'll generally find links that lead you through most of your common admin tasks.
Feature 9: Modular Architecture
Unless you've been living under a rock somewhere for the past few years, you've heard about all the problems that IIS has had when it comes to security. In earlier versions of IIS, it was either installed or it wasn't. If IIS was installed then all the features were installed. In an attempt to minimize potential vulnerability, in IIS 6, the majority of features were disabled by default, but they still got installed. This time around Microsoft has taken the next logical step. IIS7 is almost completely modular. Take a look at the installation screen:
Now granted, I've installed everything to play around with it all, but on a production server, you now have the flexibility to install only the features you need. That way if you don't use CGI, then you don't need to worry about some new bug that someone finds in the CGI handler. You also won't need to install a patch and reboot, because the affected code was never even installed on your server so there's nothing to patch
New features of C# 4.0
New features of C# 4.0
Introduction
It is now close to a year since Microsoft Visual C# 3.0 shipped as part of Visual Studio 2008. In the VS Managed Languages team we are hard at work on creating the next version of the language (with the unsurprising working title of C# 4.0), and this document is a first public description of the planned language features as we currently see them.
Please be advised that all this is in early stages of production and is subject to change. Part of the reason for sharing our plans in public so early is precisely to get the kind of feedback that will cause us to improve the final product before it rolls out.
Simultaneously with the publication of this whitepaper, a first public CTP (community technology preview) of Visual Studio 2010 is going out as a Virtual PC image for everyone to try. Please use it to play and experiment with the features, and let us know of any thoughts you have. We ask for your understanding and patience working with very early bits, where especially new or newly implemented features do not have the quality or stability of a final product. The aim of the CTP is not to give you a productive work environment but to give you the best possible impression of what we are working on for the next release.
The CTP contains a number of walkthroughs, some of which highlight the new language features of C# 4.0. Those are excellent for getting a hands-on guided tour through the details of some common scenarios for the features. You may consider this whitepaper a companion document to these walkthroughs, complementing them with a focus on the overall language features and how they work, as opposed to the specifics of the concrete scenarios.
C# 4.0
The major theme for C# 4.0 is dynamic programming. Increasingly, objects are “dynamic” in the sense that their structure and behavior is not captured by a static type, or at least not one that the compiler knows about when compiling your program. Some examples include
a. objects from dynamic programming languages, such as Python or Ruby
b. COM objects accessed through IDispatch
c. ordinary .NET types accessed through reflection
d. objects with changing structure, such as HTML DOM objects
While C# remains a statically typed language, we aim to vastly improve the interaction with such objects.
A secondary theme is co-evolution with Visual Basic. Going forward we will aim to maintain the individual character of each language, but at the same time important new features should be introduced in both languages at the same time. They should be differentiated more by style and feel than by feature set.
The new features in C# 4.0 fall into four groups:
Dynamic lookup
Dynamic lookup allows you to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the C# static type checking and instead gets resolved at runtime.
Named and optional parameters
Parameters in C# can now be specified as optional by providing a default value for them in a member declaration. When the member is invoked, optional arguments can be omitted. Furthermore, any argument can be passed by parameter name instead of position.
COM specific interop features
Dynamic lookup as well as named and optional parameters both help making programming against COM less painful than today. On top of that, however, we are adding a number of other small features that further improve the interop experience.
Variance
It used to be that an IEnumerable<string> wasn’t an IEnumerable<object>. Now it is – C# embraces type safe “co-and contravariance” and common BCL types are updated to take advantage of that.
Dynamic Lookup
Dynamic lookup allows you a unified approach to invoking things dynamically. With dynamic lookup, when you have an object in your hand you do not need to worry about whether it comes from COM, IronPython, the HTML DOM or reflection; you just apply operations to it and leave it to the runtime to figure out what exactly those operations mean for that particular object.
This affords you enormous flexibility, and can greatly simplify your code, but it does come with a significant drawback: Static typing is not maintained for these operations. A dynamic object is assumed at compile time to support any operation, and only at runtime will you get an error if it wasn’t so. Oftentimes this will be no loss, because the object wouldn’t have a static type anyway, in other cases it is a tradeoff between brevity and safety. In order to facilitate this tradeoff, it is a design goal of C# to allow you to opt in or opt out of dynamic behavior on every single call.
The dynamic type
C# 4.0 introduces a new static type called dynamic. When you have an object of type dynamic you can “do things to it” that are resolved only at runtime:
dynamic d = GetDynamicObject(…);
d.M(7);
The C# compiler allows you to call a method with any name and any arguments on d because it is of type dynamic. At runtime the actual object that d refers to will be examined to determine what it means to “call M with an int” on it.
The type dynamic can be thought of as a special version of the type object, which signals that the object can be used dynamically. It is easy to opt in or out of dynamic behavior: any object can be implicitly converted to dynamic, “suspending belief” until runtime. Conversely, there is an “assignment conversion” from dynamic to any other type, which allows implicit conversion in assignment-like constructs:
dynamic d = 7; // implicit conversion
int i = d; // assignment conversion
Dynamic operations
Not only method calls, but also field and property accesses, indexer and operator calls and even delegate invocations can be dispatched dynamically:
dynamic d = GetDynamicObject(…);
d.M(7); // calling methods
d.f = d.P; // getting and settings fields and properties
d[“one”] = d[“two”]; // getting and setting thorugh indexers
int i = d + 3; // calling operators
string s = d(5,7); // invoking as a delegate
The role of the C# compiler here is simply to package up the necessary information about “what is being done to d”, so that the runtime can pick it up and determine what the exact meaning of it is given an actual object d. Think of it as deferring part of the compiler’s job to runtime.
The result of any dynamic operation is itself of type dynamic.
Runtime lookup
At runtime a dynamic operation is dispatched according to the nature of its target object d:
COM objects
If d is a COM object, the operation is dispatched dynamically through COM IDispatch. This allows calling to COM types that don’t have a Primary Interop Assembly (PIA), and relying on COM features that don’t have a counterpart in C#, such as indexed properties and default properties.
Dynamic objects
If d implements the interface IDynamicObject d itself is asked to perform the operation. Thus by implementing IDynamicObject a type can completely redefine the meaning of dynamic operations. This is used intensively by dynamic languages such as IronPython and IronRuby to implement their own dynamic object models. It will also be used by APIs, e.g. by the HTML DOM to allow direct access to the object’s properties using property syntax.
Plain objects
Otherwise d is a standard .NET object, and the operation will be dispatched using reflection on its type and a C# “runtime binder” which implements C#’s lookup and overload resolution semantics at runtime. This is essentially a part of the C# compiler running as a runtime component to “finish the work” on dynamic operations that was deferred by the static compiler.
Example
Assume the following code:
dynamic d1 = new Foo();
dynamic d2 = new Bar();
string s;
d1.M(s, d2, 3, null);
Because the receiver of the call to M is dynamic, the C# compiler does not try to resolve the meaning of the call. Instead it stashes away information for the runtime about the call. This information (often referred to as the “payload”) is essentially equivalent to:
“Perform an instance method call of M with the following arguments:
1. a string
2. a dynamic
3. a literal int 3
4. a literal object null”
At runtime, assume that the actual type Foo of d1 is not a COM type and does not implement IDynamicObject. In this case the C# runtime binder picks up to finish the overload resolution job based on runtime type information, proceeding as follows:
1. Reflection is used to obtain the actual runtime types of the two objects, d1 and d2, that did not have a static type (or rather had the static type dynamic). The result is Foo for d1 and Bar for d2.
2. Method lookup and overload resolution is performed on the type Foo with the call M(string,Bar,3,null) using ordinary C# semantics.
3. If the method is found it is invoked; otherwise a runtime exception is thrown.
Overload resolution with dynamic arguments
Even if the receiver of a method call is of a static type, overload resolution can still happen at runtime. This can happen if one or more of the arguments have the type dynamic:
Foo foo = new Foo();
dynamic d = new Bar();
var result = foo.M(d);
The C# runtime binder will choose between the statically known overloads of M on Foo, based on the runtime type of d, namely Bar. The result is again of type dynamic.
The Dynamic Language Runtime
An important component in the underlying implementation of dynamic lookup is the Dynamic Language Runtime (DLR), which is a new API in .NET 4.0.
The DLR provides most of the infrastructure behind not only C# dynamic lookup but also the implementation of several dynamic programming languages on .NET, such as IronPython and IronRuby. Through this common infrastructure a high degree of interoperability is ensured, but just as importantly the DLR provides excellent caching mechanisms which serve to greatly enhance the efficiency of runtime dispatch.
To the user of dynamic lookup in C#, the DLR is invisible except for the improved efficiency. However, if you want to implement your own dynamically dispatched objects, the IDynamicObject interface allows you to interoperate with the DLR and plug in your own behavior. This is a rather advanced task, which requires you to understand a good deal more about the inner workings of the DLR. For API writers, however, it can definitely be worth the trouble in order to vastly improve the usability of e.g. a library representing an inherently dynamic domain.
Open issues
There are a few limitations and things that might work differently than you would expect.
· The DLR allows objects to be created from objects that represent classes. However, the current implementation of C# doesn’t have syntax to support this.
· Dynamic lookup will not be able to find extension methods. Whether extension methods apply or not depends on the static context of the call (i.e. which using clauses occur), and this context information is not currently kept as part of the payload.
· Anonymous functions (i.e. lambda expressions) cannot appear as arguments to a dynamic method call. The compiler cannot bind (i.e. “understand”) an anonymous function without knowing what type it is converted to.
One consequence of these limitations is that you cannot easily use LINQ queries over dynamic objects:
dynamic collection = …;
var result = collection.Select(e => e + 5);
If the Select method is an extension method, dynamic lookup will not find it. Even if it is an instance method, the above does not compile, because a lambda expression cannot be passed as an argument to a dynamic operation.
There are no plans to address these limitations in C# 4.0.
Named and Optional Arguments
Named and optional parameters are really two distinct features, but are often useful together. Optional parameters allow you to omit arguments to member invocations, whereas named arguments is a way to provide an argument using the name of the corresponding parameter instead of relying on its position in the parameter list.
Some APIs, most notably COM interfaces such as the Office automation APIs, are written specifically with named and optional parameters in mind. Up until now it has been very painful to call into these APIs from C#, with sometimes as many as thirty arguments having to be explicitly passed, most of which have reasonable default values and could be omitted.
Even in APIs for .NET however you sometimes find yourself compelled to write many overloads of a method with different combinations of parameters, in order to provide maximum usability to the callers. Optional parameters are a useful alternative for these situations.
Optional parameters
A parameter is declared optional simply by providing a default value for it:
public void M(int x, int y = 5, int z = 7);
Here y and z are optional parameters and can be omitted in calls:
M(1, 2, 3); // ordinary call of M
M(1, 2); // omitting z – equivalent to M(1, 2, 7)
M(1); // omitting both y and z – equivalent to M(1, 5, 7)
Named and optional arguments
C# 4.0 does not permit you to omit arguments between commas as in M(1,,3). This could lead to highly unreadable comma-counting code. Instead any argument can be passed by name. Thus if you want to omit only y from a call of M you can write:
M(1, z: 3); // passing z by name
or
M(x: 1, z: 3); // passing both x and z by name
or even
M(z: 3, x: 1); // reversing the order of arguments
All forms are equivalent, except that arguments are always evaluated in the order they appear, so in the last example the 3 is evaluated before the 1.
Optional and named arguments can be used not only with methods but also with indexers and constructors.
Overload resolution
Named and optional arguments affect overload resolution, but the changes are relatively simple:
A signature is applicable if all its parameters are either optional or have exactly one corresponding argument (by name or position) in the call which is convertible to the parameter type.
Betterness rules on conversions are only applied for arguments that are explicitly given – omitted optional arguments are ignored for betterness purposes.
If two signatures are equally good, one that does not omit optional parameters is preferred.
M(string s, int i = 1);
M(object o);
M(int i, string s = “Hello”);
M(int i);
M(5);
Given these overloads, we can see the working of the rules above. M(string,int) is not applicable because 5 doesn’t convert to string. M(int,string) is applicable because its second parameter is optional, and so, obviously are M(object) and M(int).
M(int,string) and M(int) are both better than M(object) because the conversion from 5 to int is better than the conversion from 5 to object.
Finally M(int) is better than M(int,string) because no optional arguments are omitted.
Thus the method that gets called is M(int).
Features for COM interop
Dynamic lookup as well as named and optional parameters greatly improve the experience of interoperating with COM APIs such as the Office Automation APIs. In order to remove even more of the speed bumps, a couple of small COM-specific features are also added to C# 4.0.
Dynamic import
Many COM methods accept and return variant types, which are represented in the PIAs as object. In the vast majority of cases, a programmer calling these methods already knows the static type of a returned object from context, but explicitly has to perform a cast on the returned value to make use of that knowledge. These casts are so common that they constitute a major nuisance.
In order to facilitate a smoother experience, you can now choose to import these COM APIs in such a way that variants are instead represented using the type dynamic. In other words, from your point of view, COM signatures now have occurrences of dynamic instead of object in them.
This means that you can easily access members directly off a returned object, or you can assign it to a strongly typed local variable without having to cast. To illustrate, you can now say
excel.Cells[1, 1].Value = "Hello";
instead of
((Excel.Range)excel.Cells[1, 1]).Value2 = "Hello";
and
Excel.Range range = excel.Cells[1, 1];
instead of
Excel.Range range = (Excel.Range)excel.Cells[1, 1];
Compiling without PIAs
Primary Interop Assemblies are large .NET assemblies generated from COM interfaces to facilitate strongly typed interoperability. They provide great support at design time, where your experience of the interop is as good as if the types where really defined in .NET. However, at runtime these large assemblies can easily bloat your program, and also cause versioning issues because they are distributed independently of your application.
The no-PIA feature allows you to continue to use PIAs at design time without having them around at runtime. Instead, the C# compiler will bake the small part of the PIA that a program actually uses directly into its assembly. At runtime the PIA does not have to be loaded.
Omitting ref
Because of a different programming model, many COM APIs contain a lot of reference parameters. Contrary to refs in C#, these are typically not meant to mutate a passed-in argument for the subsequent benefit of the caller, but are simply another way of passing value parameters.
It therefore seems unreasonable that a C# programmer should have to create temporary variables for all such ref parameters and pass these by reference. Instead, specifically for COM methods, the C# compiler will allow you to pass arguments by value to such a method, and will automatically generate temporary variables to hold the passed-in values, subsequently discarding these when the call returns. In this way the caller sees value semantics, and will not experience any side effects, but the called method still gets a reference.
Open issues
A few COM interface features still are not surfaced in C#. Most notably these include indexed properties and default properties. As mentioned above these will be respected if you access COM dynamically, but statically typed C# code will still not recognize them.
There are currently no plans to address these remaining speed bumps in C# 4.0.
Variance
An aspect of generics that often comes across as surprising is that the following is illegal:
IList<string> strings = new List<string>();
IList<object> objects = strings;
The second assignment is disallowed because strings does not have the same element type as objects. There is a perfectly good reason for this. If it were allowed you could write:
objects[0] = 5;
string s = strings[0];
Allowing an int to be inserted into a list of strings and subsequently extracted as a string. This would be a breach of type safety.
However, there are certain interfaces where the above cannot occur, notably where there is no way to insert an object into the collection. Such an interface is IEnumerable<T>. If instead you say:
IEnumerable<object> objects = strings;
There is no way we can put the wrong kind of thing into strings through objects, because objects doesn’t have a method that takes an element in. Variance is about allowing assignments such as this in cases where it is safe. The result is that a lot of situations that were previously surprising now just work.
Covariance
In .NET 4.0 the IEnumerable<T> interface will be declared in the following way:
public interface IEnumerable<out T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}
public interface IEnumerator<out T> : IEnumerator
{
bool MoveNext();
T Current { get; }
}
The “out” in these declarations signifies that the T can only occur in output position in the interface – the compiler will complain otherwise. In return for this restriction, the interface becomes “covariant” in T, which means that an IEnumerable<A> is considered an IEnumerable<B> if A has a reference conversion to B.
As a result, any sequence of strings is also e.g. a sequence of objects.
This is useful e.g. in many LINQ methods. Using the declarations above:
var result = strings.Union(objects); // succeeds with an IEnumerable<object>
This would previously have been disallowed, and you would have had to to some cumbersome wrapping to get the two sequences to have the same element type.
Contravariance
Type parameters can also have an “in” modifier, restricting them to occur only in input positions. An example is IComparer<T>:
public interface IComparer<in T>
{
public int Compare(T left, T right);
}
The somewhat baffling result is that an IComparer<object> can in fact be considered an IComparer<string>! It makes sense when you think about it: If a comparer can compare any two objects, it can certainly also compare two strings. This property is referred to as contravariance.
A generic type can have both in and out modifiers on its type parameters, as is the case with the Func<…> delegate types:
public delegate TResult Func<in TArg, out TResult>(TArg arg);
Obviously the argument only ever comes in, and the result only ever comes out. Therefore a Func<object,string> can in fact be used as a Func<string,object>.
Limitations
Variant type parameters can only be declared on interfaces and delegate types, due to a restriction in the CLR. Variance only applies when there is a reference conversion between the type arguments. For instance, an IEnumerable<int> is not an IEnumerable<object> because the conversion from int to object is a boxing conversion, not a reference conversion.
Also please note that the CTP does not contain the new versions of the .NET types mentioned above. In order to experiment with variance you have to declare your own variant interfaces and delegate types.
COM Example
Here is a larger Office automation example that shows many of the new C# features in action.
using System;
using System.Diagnostics;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
class Program
{
static void Main(string[] args) {
var excel = new Excel.Application();
excel.Visible = true;
excel.Workbooks.Add(); // optional arguments omitted
excel.Cells[1, 1].Value = "Process Name"; // no casts; Value dynamically
excel.Cells[1, 2].Value = "Memory Usage"; // accessed
var processes = Process.GetProcesses()
.OrderByDescending(p => p.WorkingSet)
.Take(10);
int i = 2;
foreach (var p in processes) {
excel.Cells[i, 1].Value = p.ProcessName; // no casts
excel.Cells[i, 2].Value = p.WorkingSet; // no casts
i++;
}
Excel.Range range = excel.Cells[1, 1]; // no casts
Excel.Chart chart = excel.ActiveWorkbook.Charts.
Add(After: excel.ActiveSheet); // named and optional arguments
chart.ChartWizard(
Source: range.CurrentRegion,
Title: "Memory Usage in " + Environment.MachineName); //named+optional
chart.ChartStyle = 45;
chart.CopyPicture(Excel.XlPictureAppearance.xlScreen,
Excel.XlCopyPictureFormat.xlBitmap,
Excel.XlPictureAppearance.xlScreen);
var word = new Word.Application();
word.Visible = true;
word.Documents.Add(); // optional arguments
word.Selection.Paste();
}
}
The code is much more terse and readable than the C# 3.0 counterpart.
Note especially how the Value property is accessed dynamically. This is actually an indexed property, i.e. a property that takes an argument; something which C# does not understand. However the argument is optional. Since the access is dynamic, it goes through the runtime COM binder which knows to substitute the default value and call the indexed property. Thus, dynamic COM allows you to avoid accesses to the puzzling Value2 property of Excel ranges.
Relationship with Visual Basic
A number of the features introduced to C# 4.0 already exist or will be introduced in some form or other in Visual Basic:
· Late binding in VB is similar in many ways to dynamic lookup in C#, and can be expected to make more use of the DLR in the future, leading to further parity with C#.
· Named and optional arguments have been part of Visual Basic for a long time, and the C# version of the feature is explicitly engineered with maximal VB interoperability in mind.
· NoPIA and variance are both being introduced to VB and C# at the same time.
VB in turn is adding a number of features that have hitherto been a mainstay of C#. As a result future versions of C# and VB will have much better feature parity, for the benefit of everyone.
Introduction
It is now close to a year since Microsoft Visual C# 3.0 shipped as part of Visual Studio 2008. In the VS Managed Languages team we are hard at work on creating the next version of the language (with the unsurprising working title of C# 4.0), and this document is a first public description of the planned language features as we currently see them.
Please be advised that all this is in early stages of production and is subject to change. Part of the reason for sharing our plans in public so early is precisely to get the kind of feedback that will cause us to improve the final product before it rolls out.
Simultaneously with the publication of this whitepaper, a first public CTP (community technology preview) of Visual Studio 2010 is going out as a Virtual PC image for everyone to try. Please use it to play and experiment with the features, and let us know of any thoughts you have. We ask for your understanding and patience working with very early bits, where especially new or newly implemented features do not have the quality or stability of a final product. The aim of the CTP is not to give you a productive work environment but to give you the best possible impression of what we are working on for the next release.
The CTP contains a number of walkthroughs, some of which highlight the new language features of C# 4.0. Those are excellent for getting a hands-on guided tour through the details of some common scenarios for the features. You may consider this whitepaper a companion document to these walkthroughs, complementing them with a focus on the overall language features and how they work, as opposed to the specifics of the concrete scenarios.
C# 4.0
The major theme for C# 4.0 is dynamic programming. Increasingly, objects are “dynamic” in the sense that their structure and behavior is not captured by a static type, or at least not one that the compiler knows about when compiling your program. Some examples include
a. objects from dynamic programming languages, such as Python or Ruby
b. COM objects accessed through IDispatch
c. ordinary .NET types accessed through reflection
d. objects with changing structure, such as HTML DOM objects
While C# remains a statically typed language, we aim to vastly improve the interaction with such objects.
A secondary theme is co-evolution with Visual Basic. Going forward we will aim to maintain the individual character of each language, but at the same time important new features should be introduced in both languages at the same time. They should be differentiated more by style and feel than by feature set.
The new features in C# 4.0 fall into four groups:
Dynamic lookup
Dynamic lookup allows you to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the C# static type checking and instead gets resolved at runtime.
Named and optional parameters
Parameters in C# can now be specified as optional by providing a default value for them in a member declaration. When the member is invoked, optional arguments can be omitted. Furthermore, any argument can be passed by parameter name instead of position.
COM specific interop features
Dynamic lookup as well as named and optional parameters both help making programming against COM less painful than today. On top of that, however, we are adding a number of other small features that further improve the interop experience.
Variance
It used to be that an IEnumerable<string> wasn’t an IEnumerable<object>. Now it is – C# embraces type safe “co-and contravariance” and common BCL types are updated to take advantage of that.
Dynamic Lookup
Dynamic lookup allows you a unified approach to invoking things dynamically. With dynamic lookup, when you have an object in your hand you do not need to worry about whether it comes from COM, IronPython, the HTML DOM or reflection; you just apply operations to it and leave it to the runtime to figure out what exactly those operations mean for that particular object.
This affords you enormous flexibility, and can greatly simplify your code, but it does come with a significant drawback: Static typing is not maintained for these operations. A dynamic object is assumed at compile time to support any operation, and only at runtime will you get an error if it wasn’t so. Oftentimes this will be no loss, because the object wouldn’t have a static type anyway, in other cases it is a tradeoff between brevity and safety. In order to facilitate this tradeoff, it is a design goal of C# to allow you to opt in or opt out of dynamic behavior on every single call.
The dynamic type
C# 4.0 introduces a new static type called dynamic. When you have an object of type dynamic you can “do things to it” that are resolved only at runtime:
dynamic d = GetDynamicObject(…);
d.M(7);
The C# compiler allows you to call a method with any name and any arguments on d because it is of type dynamic. At runtime the actual object that d refers to will be examined to determine what it means to “call M with an int” on it.
The type dynamic can be thought of as a special version of the type object, which signals that the object can be used dynamically. It is easy to opt in or out of dynamic behavior: any object can be implicitly converted to dynamic, “suspending belief” until runtime. Conversely, there is an “assignment conversion” from dynamic to any other type, which allows implicit conversion in assignment-like constructs:
dynamic d = 7; // implicit conversion
int i = d; // assignment conversion
Dynamic operations
Not only method calls, but also field and property accesses, indexer and operator calls and even delegate invocations can be dispatched dynamically:
dynamic d = GetDynamicObject(…);
d.M(7); // calling methods
d.f = d.P; // getting and settings fields and properties
d[“one”] = d[“two”]; // getting and setting thorugh indexers
int i = d + 3; // calling operators
string s = d(5,7); // invoking as a delegate
The role of the C# compiler here is simply to package up the necessary information about “what is being done to d”, so that the runtime can pick it up and determine what the exact meaning of it is given an actual object d. Think of it as deferring part of the compiler’s job to runtime.
The result of any dynamic operation is itself of type dynamic.
Runtime lookup
At runtime a dynamic operation is dispatched according to the nature of its target object d:
COM objects
If d is a COM object, the operation is dispatched dynamically through COM IDispatch. This allows calling to COM types that don’t have a Primary Interop Assembly (PIA), and relying on COM features that don’t have a counterpart in C#, such as indexed properties and default properties.
Dynamic objects
If d implements the interface IDynamicObject d itself is asked to perform the operation. Thus by implementing IDynamicObject a type can completely redefine the meaning of dynamic operations. This is used intensively by dynamic languages such as IronPython and IronRuby to implement their own dynamic object models. It will also be used by APIs, e.g. by the HTML DOM to allow direct access to the object’s properties using property syntax.
Plain objects
Otherwise d is a standard .NET object, and the operation will be dispatched using reflection on its type and a C# “runtime binder” which implements C#’s lookup and overload resolution semantics at runtime. This is essentially a part of the C# compiler running as a runtime component to “finish the work” on dynamic operations that was deferred by the static compiler.
Example
Assume the following code:
dynamic d1 = new Foo();
dynamic d2 = new Bar();
string s;
d1.M(s, d2, 3, null);
Because the receiver of the call to M is dynamic, the C# compiler does not try to resolve the meaning of the call. Instead it stashes away information for the runtime about the call. This information (often referred to as the “payload”) is essentially equivalent to:
“Perform an instance method call of M with the following arguments:
1. a string
2. a dynamic
3. a literal int 3
4. a literal object null”
At runtime, assume that the actual type Foo of d1 is not a COM type and does not implement IDynamicObject. In this case the C# runtime binder picks up to finish the overload resolution job based on runtime type information, proceeding as follows:
1. Reflection is used to obtain the actual runtime types of the two objects, d1 and d2, that did not have a static type (or rather had the static type dynamic). The result is Foo for d1 and Bar for d2.
2. Method lookup and overload resolution is performed on the type Foo with the call M(string,Bar,3,null) using ordinary C# semantics.
3. If the method is found it is invoked; otherwise a runtime exception is thrown.
Overload resolution with dynamic arguments
Even if the receiver of a method call is of a static type, overload resolution can still happen at runtime. This can happen if one or more of the arguments have the type dynamic:
Foo foo = new Foo();
dynamic d = new Bar();
var result = foo.M(d);
The C# runtime binder will choose between the statically known overloads of M on Foo, based on the runtime type of d, namely Bar. The result is again of type dynamic.
The Dynamic Language Runtime
An important component in the underlying implementation of dynamic lookup is the Dynamic Language Runtime (DLR), which is a new API in .NET 4.0.
The DLR provides most of the infrastructure behind not only C# dynamic lookup but also the implementation of several dynamic programming languages on .NET, such as IronPython and IronRuby. Through this common infrastructure a high degree of interoperability is ensured, but just as importantly the DLR provides excellent caching mechanisms which serve to greatly enhance the efficiency of runtime dispatch.
To the user of dynamic lookup in C#, the DLR is invisible except for the improved efficiency. However, if you want to implement your own dynamically dispatched objects, the IDynamicObject interface allows you to interoperate with the DLR and plug in your own behavior. This is a rather advanced task, which requires you to understand a good deal more about the inner workings of the DLR. For API writers, however, it can definitely be worth the trouble in order to vastly improve the usability of e.g. a library representing an inherently dynamic domain.
Open issues
There are a few limitations and things that might work differently than you would expect.
· The DLR allows objects to be created from objects that represent classes. However, the current implementation of C# doesn’t have syntax to support this.
· Dynamic lookup will not be able to find extension methods. Whether extension methods apply or not depends on the static context of the call (i.e. which using clauses occur), and this context information is not currently kept as part of the payload.
· Anonymous functions (i.e. lambda expressions) cannot appear as arguments to a dynamic method call. The compiler cannot bind (i.e. “understand”) an anonymous function without knowing what type it is converted to.
One consequence of these limitations is that you cannot easily use LINQ queries over dynamic objects:
dynamic collection = …;
var result = collection.Select(e => e + 5);
If the Select method is an extension method, dynamic lookup will not find it. Even if it is an instance method, the above does not compile, because a lambda expression cannot be passed as an argument to a dynamic operation.
There are no plans to address these limitations in C# 4.0.
Named and Optional Arguments
Named and optional parameters are really two distinct features, but are often useful together. Optional parameters allow you to omit arguments to member invocations, whereas named arguments is a way to provide an argument using the name of the corresponding parameter instead of relying on its position in the parameter list.
Some APIs, most notably COM interfaces such as the Office automation APIs, are written specifically with named and optional parameters in mind. Up until now it has been very painful to call into these APIs from C#, with sometimes as many as thirty arguments having to be explicitly passed, most of which have reasonable default values and could be omitted.
Even in APIs for .NET however you sometimes find yourself compelled to write many overloads of a method with different combinations of parameters, in order to provide maximum usability to the callers. Optional parameters are a useful alternative for these situations.
Optional parameters
A parameter is declared optional simply by providing a default value for it:
public void M(int x, int y = 5, int z = 7);
Here y and z are optional parameters and can be omitted in calls:
M(1, 2, 3); // ordinary call of M
M(1, 2); // omitting z – equivalent to M(1, 2, 7)
M(1); // omitting both y and z – equivalent to M(1, 5, 7)
Named and optional arguments
C# 4.0 does not permit you to omit arguments between commas as in M(1,,3). This could lead to highly unreadable comma-counting code. Instead any argument can be passed by name. Thus if you want to omit only y from a call of M you can write:
M(1, z: 3); // passing z by name
or
M(x: 1, z: 3); // passing both x and z by name
or even
M(z: 3, x: 1); // reversing the order of arguments
All forms are equivalent, except that arguments are always evaluated in the order they appear, so in the last example the 3 is evaluated before the 1.
Optional and named arguments can be used not only with methods but also with indexers and constructors.
Overload resolution
Named and optional arguments affect overload resolution, but the changes are relatively simple:
A signature is applicable if all its parameters are either optional or have exactly one corresponding argument (by name or position) in the call which is convertible to the parameter type.
Betterness rules on conversions are only applied for arguments that are explicitly given – omitted optional arguments are ignored for betterness purposes.
If two signatures are equally good, one that does not omit optional parameters is preferred.
M(string s, int i = 1);
M(object o);
M(int i, string s = “Hello”);
M(int i);
M(5);
Given these overloads, we can see the working of the rules above. M(string,int) is not applicable because 5 doesn’t convert to string. M(int,string) is applicable because its second parameter is optional, and so, obviously are M(object) and M(int).
M(int,string) and M(int) are both better than M(object) because the conversion from 5 to int is better than the conversion from 5 to object.
Finally M(int) is better than M(int,string) because no optional arguments are omitted.
Thus the method that gets called is M(int).
Features for COM interop
Dynamic lookup as well as named and optional parameters greatly improve the experience of interoperating with COM APIs such as the Office Automation APIs. In order to remove even more of the speed bumps, a couple of small COM-specific features are also added to C# 4.0.
Dynamic import
Many COM methods accept and return variant types, which are represented in the PIAs as object. In the vast majority of cases, a programmer calling these methods already knows the static type of a returned object from context, but explicitly has to perform a cast on the returned value to make use of that knowledge. These casts are so common that they constitute a major nuisance.
In order to facilitate a smoother experience, you can now choose to import these COM APIs in such a way that variants are instead represented using the type dynamic. In other words, from your point of view, COM signatures now have occurrences of dynamic instead of object in them.
This means that you can easily access members directly off a returned object, or you can assign it to a strongly typed local variable without having to cast. To illustrate, you can now say
excel.Cells[1, 1].Value = "Hello";
instead of
((Excel.Range)excel.Cells[1, 1]).Value2 = "Hello";
and
Excel.Range range = excel.Cells[1, 1];
instead of
Excel.Range range = (Excel.Range)excel.Cells[1, 1];
Compiling without PIAs
Primary Interop Assemblies are large .NET assemblies generated from COM interfaces to facilitate strongly typed interoperability. They provide great support at design time, where your experience of the interop is as good as if the types where really defined in .NET. However, at runtime these large assemblies can easily bloat your program, and also cause versioning issues because they are distributed independently of your application.
The no-PIA feature allows you to continue to use PIAs at design time without having them around at runtime. Instead, the C# compiler will bake the small part of the PIA that a program actually uses directly into its assembly. At runtime the PIA does not have to be loaded.
Omitting ref
Because of a different programming model, many COM APIs contain a lot of reference parameters. Contrary to refs in C#, these are typically not meant to mutate a passed-in argument for the subsequent benefit of the caller, but are simply another way of passing value parameters.
It therefore seems unreasonable that a C# programmer should have to create temporary variables for all such ref parameters and pass these by reference. Instead, specifically for COM methods, the C# compiler will allow you to pass arguments by value to such a method, and will automatically generate temporary variables to hold the passed-in values, subsequently discarding these when the call returns. In this way the caller sees value semantics, and will not experience any side effects, but the called method still gets a reference.
Open issues
A few COM interface features still are not surfaced in C#. Most notably these include indexed properties and default properties. As mentioned above these will be respected if you access COM dynamically, but statically typed C# code will still not recognize them.
There are currently no plans to address these remaining speed bumps in C# 4.0.
Variance
An aspect of generics that often comes across as surprising is that the following is illegal:
IList<string> strings = new List<string>();
IList<object> objects = strings;
The second assignment is disallowed because strings does not have the same element type as objects. There is a perfectly good reason for this. If it were allowed you could write:
objects[0] = 5;
string s = strings[0];
Allowing an int to be inserted into a list of strings and subsequently extracted as a string. This would be a breach of type safety.
However, there are certain interfaces where the above cannot occur, notably where there is no way to insert an object into the collection. Such an interface is IEnumerable<T>. If instead you say:
IEnumerable<object> objects = strings;
There is no way we can put the wrong kind of thing into strings through objects, because objects doesn’t have a method that takes an element in. Variance is about allowing assignments such as this in cases where it is safe. The result is that a lot of situations that were previously surprising now just work.
Covariance
In .NET 4.0 the IEnumerable<T> interface will be declared in the following way:
public interface IEnumerable<out T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}
public interface IEnumerator<out T> : IEnumerator
{
bool MoveNext();
T Current { get; }
}
The “out” in these declarations signifies that the T can only occur in output position in the interface – the compiler will complain otherwise. In return for this restriction, the interface becomes “covariant” in T, which means that an IEnumerable<A> is considered an IEnumerable<B> if A has a reference conversion to B.
As a result, any sequence of strings is also e.g. a sequence of objects.
This is useful e.g. in many LINQ methods. Using the declarations above:
var result = strings.Union(objects); // succeeds with an IEnumerable<object>
This would previously have been disallowed, and you would have had to to some cumbersome wrapping to get the two sequences to have the same element type.
Contravariance
Type parameters can also have an “in” modifier, restricting them to occur only in input positions. An example is IComparer<T>:
public interface IComparer<in T>
{
public int Compare(T left, T right);
}
The somewhat baffling result is that an IComparer<object> can in fact be considered an IComparer<string>! It makes sense when you think about it: If a comparer can compare any two objects, it can certainly also compare two strings. This property is referred to as contravariance.
A generic type can have both in and out modifiers on its type parameters, as is the case with the Func<…> delegate types:
public delegate TResult Func<in TArg, out TResult>(TArg arg);
Obviously the argument only ever comes in, and the result only ever comes out. Therefore a Func<object,string> can in fact be used as a Func<string,object>.
Limitations
Variant type parameters can only be declared on interfaces and delegate types, due to a restriction in the CLR. Variance only applies when there is a reference conversion between the type arguments. For instance, an IEnumerable<int> is not an IEnumerable<object> because the conversion from int to object is a boxing conversion, not a reference conversion.
Also please note that the CTP does not contain the new versions of the .NET types mentioned above. In order to experiment with variance you have to declare your own variant interfaces and delegate types.
COM Example
Here is a larger Office automation example that shows many of the new C# features in action.
using System;
using System.Diagnostics;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
class Program
{
static void Main(string[] args) {
var excel = new Excel.Application();
excel.Visible = true;
excel.Workbooks.Add(); // optional arguments omitted
excel.Cells[1, 1].Value = "Process Name"; // no casts; Value dynamically
excel.Cells[1, 2].Value = "Memory Usage"; // accessed
var processes = Process.GetProcesses()
.OrderByDescending(p => p.WorkingSet)
.Take(10);
int i = 2;
foreach (var p in processes) {
excel.Cells[i, 1].Value = p.ProcessName; // no casts
excel.Cells[i, 2].Value = p.WorkingSet; // no casts
i++;
}
Excel.Range range = excel.Cells[1, 1]; // no casts
Excel.Chart chart = excel.ActiveWorkbook.Charts.
Add(After: excel.ActiveSheet); // named and optional arguments
chart.ChartWizard(
Source: range.CurrentRegion,
Title: "Memory Usage in " + Environment.MachineName); //named+optional
chart.ChartStyle = 45;
chart.CopyPicture(Excel.XlPictureAppearance.xlScreen,
Excel.XlCopyPictureFormat.xlBitmap,
Excel.XlPictureAppearance.xlScreen);
var word = new Word.Application();
word.Visible = true;
word.Documents.Add(); // optional arguments
word.Selection.Paste();
}
}
The code is much more terse and readable than the C# 3.0 counterpart.
Note especially how the Value property is accessed dynamically. This is actually an indexed property, i.e. a property that takes an argument; something which C# does not understand. However the argument is optional. Since the access is dynamic, it goes through the runtime COM binder which knows to substitute the default value and call the indexed property. Thus, dynamic COM allows you to avoid accesses to the puzzling Value2 property of Excel ranges.
Relationship with Visual Basic
A number of the features introduced to C# 4.0 already exist or will be introduced in some form or other in Visual Basic:
· Late binding in VB is similar in many ways to dynamic lookup in C#, and can be expected to make more use of the DLR in the future, leading to further parity with C#.
· Named and optional arguments have been part of Visual Basic for a long time, and the C# version of the feature is explicitly engineered with maximal VB interoperability in mind.
· NoPIA and variance are both being introduced to VB and C# at the same time.
VB in turn is adding a number of features that have hitherto been a mainstay of C#. As a result future versions of C# and VB will have much better feature parity, for the benefit of everyone.
New Features of .NET Framework 4.0
27 New Features of .NET Framework 4.0
The new features and improvements are described in the following sections:
Programming Languages
Common Language Runtime (CLR)
Base Class Libraries
Networking
Web
Client
Data
Communications
Workflow
Common Language Runtime (CLR)
The following sections describe new features in security, parallel computing, performance and diagnostics, dynamic language runtime, and other CLR-related technologies.
Security
The .NET Framework 4.0 provides simplifications, improvements, and expanded capabilities in the security model. For more information, see Security Changes in the .NET Framework 4.
Parallel Computing
The .NET Framework 4.0 introduces a new programming model for writing multithreaded and asynchronous code that greatly simplifies the work of application and library developers. The new model enables developers to write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool. The new Parallel and Task classes, and other related types, support this new model. Parallel LINQ (PLINQ), which is a parallel implementation of LINQ to Objects, enables similar functionality through declarative syntax. For more information, see Parallel Programming in the .NET Framework.
Performance and Diagnostics
In addition to the following features, the .NET Framework 4.0 provides improvements in startup time, working set sizes, and faster performance for multithreaded applications.
ETW Events
You can now access the Event Tracing for Windows (ETW) events for diagnostic purposes to improve performance. For more information, see the following topics:
CLR ETW Events
Using Event Tracing for Windows to Log CLR Events
Performance Monitor (Perfmon.exe) now enables you to disambiguate multiple applications that use the same name and multiple versions of the common language runtime loaded by a single process. This requires a simple registry modification. For more information, see Performance Counters and In-Process Side-By-Side Applications.
Code Contracts
Code contracts let you specify contractual information that is not represented by a method's or type's signature alone. The new System.Diagnostics.Contracts namespace contains classes that provide a language-neutral way to express coding assumptions in the form of pre-conditions, post-conditions, and object invariants. The contracts improve testing with run-time checking, enable static contract verification, and documentation generation.
The applicable scenarios include the following:
Perform static bug finding, which enables some bugs to be found without executing the code.
Create guidance for automated testing tools to enhance test coverage.
Create a standard notation for code behavior, which provides more information for documentation.
Lazy Initialiation
With lazy initialization, the memory for an object is not allocated until it is needed. Lazy initialization can improve performance by spreading object allocations evenly across the lifetime of a program. You can enable lazy initialization for any custom type by wrapping the type inside a System..::.Lazy<(Of <(T>)>) class.
Dynamic Language Runtime
The dynamic language runtime (DLR) is a new runtime environment that adds a set of services for dynamic languages to the CLR. The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. To support the DLR, the new System.Dynamic namespace is added to the .NET Framework. In addition, several new classes that support the .NET Framework infrastructure are added to the System.Runtime.CompilerServices namespace. For more information, see Dynamic Language Runtime Overview.
In-Process Side-by-Side Execution
In-process side-by-side hosting enables an application to load and activate multiple versions of the common language runtime (CLR) in the same process. For example, you can run applications that are based on the .NET Framework 2.0 SP1 and applications that are based on .NET Framework 4.0 in the same process. Older components continue to use the same CLR version, and new components use the new CLR version. For more information, see Hosting Changes in the .NET Framework 4.
Interoperability
New interoperability features and improvements include the following:
You no longer have to use primary interop assemblies (PIAs). Compilers embed the parts of the interop assemblies that the add-ins actually use, and type safety is ensured by the common language runtime.
You can use the System.Runtime.InteropServices..::.ICustomQueryInterface interface to create a customized, managed code implementation of the IUnknown::QueryInterface method. Applications can use the customized implementation to return a specific interface (except IUnknown) for a particular interface ID.
Profiling
In the .NET Framework 4.0, you can attach profilers to a running process at any point, perform the requested profiling tasks, and then detach. For more information, see the [IClrProfiling::AttachProfiler]IClrProfiling Interface::AttachProfiler Method method.
Garbage Collection
The .NET Framework 4.0 provides background garbage collection; for more information, see the entry So, what’s new in the CLR 4.0 GC? in the CLR Garbage Collector blog.
Covariance and Contravariance
Several generic interfaces and delegates now support covariance and contravariance. For more information, see Covariance and Contravariance in the Common Language Runtime.
Base Class Libraries
The following sections describe new features in collections and data structures, exception handling, I/O, reflection, threading, and Windows registry.
Collections and Data Structures
Enhancements in this area include the new System.Numerics..::.BigInteger structure, the System.Collections.Generic..::.SortedSet<(Of <(T>)>) generic class, and tuples.
BigInteger
The new System.Numerics..::.BigInteger structure is an arbitrary-precision integer data type that supports all the standard integer operations, including bit manipulation. It can be used from any .NET Framework language. In addition, some of the new .NET Framework languages (such as F# and IronPython) have built-in support for this structure.
SortedSet Generic Class
The new System.Collections.Generic..::.SortedSet<(Of <(T>)>) class provides a self-balancing tree that maintains data in sorted order after insertions, deletions, and searches. This class implements the new System.Collections.Generic..::.ISet<(Of <(T>)>) interface.
The System.Collections.Generic..::.HashSet<(Of <(T>)>) class also implements the ISet<(Of <(T>)>) interface.
Tuples
A tuple is a simple generic data structure that holds an ordered set of items of heterogeneous types. Tuples are supported natively in languages such as F# and IronPython, but are also easy to use from any .NET Framework language such as C# and Visual Basic. The ..NET Framework 4.0 adds eight new generic tuple classes, and also a Tuple class that contains static factory methods for creating tuples.
Exceptions Handling
The .NET Framework 4.0 class library contains the new System.Runtime.ExceptionServices namespace, and adds the ability to handle corrupted state exceptions.
Corrupted State Exceptions
The CLR no longer delivers corrupted state exceptions that occur in the operating system to be handled by managed code, unless you apply the HandleProcessCorruptedStateExceptionsAttribute attribute to the method that handles the corrupted state exception.
Alternatively, you can add the following setting to an application's configuration file:
legacyCorruptedStateExceptionsPolicy=true
I/O
The key new features in I/O are efficient file enumerations, memory-mapped files, and improvements in isolated storage and compression.
File System Enumeration Improvements
New enumeration methods in the Directory and DirectoryInfo classes return IEnumerable<(Of <(T>)>) collections instead of arrays. These methods are more efficient than the array-based methods, because they do not have to allocate a (potentially large) array and you can access the first results immediately instead of waiting for the complete enumeration to occur.
There are also new methods in the static File class that read and write lines from files by using IEnumerable<(Of <(T>)>) collections. These methods are useful in LINQ scenarios where you may want to quickly and efficiently query the contents of a text file and write out the results to a log file without allocating any arrays.
Memory-Mapped Files
The new System.IO.MemoryMappedFiles namespace provides memory mapping functionality, which is available in Windows. You can use memory-mapped files to edit very large files and to create shared memory for inter-process communication. The new System.IO..::.UnmanagedMemoryAccessor class enables random access to unmanaged memory, similar to how System.IO..::.UnmanagedMemoryStream enables sequential access to unmanaged memory.
Isolated Storage Improvements
Partial-trust applications, such as Windows Presentation Framework (WPF) browser applications (XBAPs) and ClickOnce partial-trust applications, now have the same capabilities in the .NET Framework as they do in Silverlight. The default quota size is doubled, and applications can prompt the user to approve or reject a request to increase the quota. The System.IO.IsolatedStorage..::.IsolatedStorageFile class contains new members to manage the quota and to make working with files and directories easier.
Compression Improvements
The compression algorithms for the System.IO.Compression..::.DeflateStream and System.IO.Compression..::.GZipStream classes have improved so that data that is already compressed is no longer inflated. This results in much better compression ratios. Also, the 4-gigabyte size restriction for compressing streams has been removed.
Reflection
The .NET Framework 4.0 provides the capability to monitor the performance of your application domains.
Application Domain Resource Monitoring
Until now, there has been no way to determine whether a particular application domain is affecting other application domains, because the operating system APIs and tools, such as the Windows Task Manager, were precise only to the process level. Starting with the .NET Framework 4.0, you can get processor usage and memory usage estimates per application domain.
Application domain resource monitoring is available through the managed AppDomain class, native hosting APIs, and event tracing for Windows (ETW). When this feature has been enabled, it collects statistics on all application domains in the process for the life of the process.
For more information, see the Element, and the following properties in the AppDomain class:
MonitoringIsEnabled
MonitoringSurvivedMemorySize
MonitoringSurvivedProcessMemorySize
MonitoringTotalAllocatedMemorySize
MonitoringTotalProcessorTime
64-bit View and Other Registry Improvements
Windows registry improvements include the following:
Ability to specify a 32-bit or 64-bit view of the registry with the Microsoft.Win32..::.RegistryView enumeration when you open base keys.
the new Microsoft.Win32..::.RegistryOptions enumeration, which lets you specify a volatile registry key that does not persist after the computer restarts.
Threading
General threading improvements include the following:
The new Monitor..::.Enter(Object, Boolean%) method overload takes a Boolean reference and atomically sets it to true only if the monitor is successfully entered.
You can use the Thread..::.Yield method to have the calling thread yield execution to another thread that is ready to run on the current processor.
The following sections describe new threading features.
Unified Model for Cancellation
The .NET Framework 4.0 provides a new unified model for cancellation of asynchronous operations. The new System.Threading..::.CancellationTokenSource class is used to create a CancellationToken that may be passed to any number of operations on multiple threads. By calling Cancel()()() on the token source object, the IsCancellationRequested property on the token is set to true and the token’s wait handle is signaled, at which time any registered actions with the token are invoked. Any object that has a reference to that token can monitor the value of that property and respond as appropriate.
Thread-Safe Collection Classes
The new System.Collections.Concurrent namespace introduces several new thread-safe collection classes that provide lock-free access to items whenever useful, and fine-grained locking when locks are appropriate. The use of these classes in multi-threaded scenarios should improve performance over collection types such as ArrayList, and List<(Of <(T>)>).
Synchronization Primitives
New synchronization primitives in the System.Threading namespace enable fine-grained concurrency and faster performance by avoiding expensive locking mechanisms. The Barrier class enables multiple threads to work on an algorithm cooperatively by providing a point at which each task can signal its arrival and then block until the other participants in the barrier have arrived. The CountdownEvent class simplifies fork and join scenarios by providing an easy rendezvous mechanism. The ManualResetEventSlim class is a lock-free synchronization primitive similar to the ManualResetEvent class. ManualResetEventSlim is lighter weight but can only be used for intra-process communication. The SemaphoreSlim class is a lightweight synchronization primitive that limits the number of threads that can access a resource or a pool of resources at the same time; it can be used only for intra-process communication. The SpinLock class is a mutual exclusion lock primitive that causes the thread that is trying to acquire the lock to wait in a loop, or spin, until the lock becomes available. The SpinWait class is a small, lightweight type that will spin for a time and eventually put the thread into a wait state if the spin count is exceeded.
Networking
Enhancements have been made that affect how integrated Windows authentication is handled by the HttpWebRequest, HttpListener, SmtpClient, SslStream, NegotiateStream, and related classes in the System.Net and related namespaces. Support was added for extended protection to enhance security. The changes to support extended protection are available only for applications on Windows 7. The extended protection features are not available on earlier versions of Windows. For more information, seeIntegrated Windows Authentication with Extended Protection.
Web
The following sections describe new features in ASP.NET core services, Web Forms, Dynamic Data, and Visual Web Developer.
ASP.NET Core Services
ASP.NET introduces several features that improve core ASP.NET services, Web Forms, Dynamic Data, and Visual Web Developer. For more information, see What’s New in ASP.NET and Web Development.
ASP.NET Web Forms
Web Forms has been a core feature in ASP.NET since the release of ASP.NET 1.0. Many enhancements have been made in this area for ASP.NET 4, including the following:
The ability to set meta tags.
More control over view state.
Easier ways to work with browser capabilities.
Support for using ASP.NET routing with Web Forms.
More control over generated IDs.
The ability to persist selected rows in data controls.
More control over rendered HTML in the FormView and ListView controls.
Filtering support for data source controls.
Dynamic Data
For ASP.NET 4, Dynamic Data has been enhanced to give developers even more power for quickly building data-driven Web sites. This includes the following:
Automatic validation that is based on constraints defined in the data model.
The ability to easily change the markup that is generated for fields in the GridView and DetailsView controls by using field templates that are part of your Dynamic Data project.
Visual Web Developer Enhancements
The Web page designer in Visual Studio 2010 has been enhanced for better CSS compatibility, includes additional support for HTML and ASP.NET markup code examples, and features a redesigned version of IntelliSense for JScript. In addition, two new deployment features called Web packaging and One-Click Publish make deploying Web applications easier.
Client
The following sections describe new features in Windows Presentation Foundation (WPF) and Managed Extensibility Framework (MEF).
Windows Presentation Foundation
In the .NET Framework 4.0, Windows Presentation Foundation (WPF) contains changes and improvements in many areas. This includes controls, graphics, and XAML.
For more information, see What's New in Windows Presentation Foundation Version 4.
Managed Extensibility Framework
The Managed Extensibility Framework (MEF) is a new library in the .NET Framework 4.0 that enables you to build extensible and composable applications. MEF enables application developers to specify points where an application can be extended, expose services to offer to other extensible applications, and create parts for consumption by extensible applications. It also enables easy discoverability of available parts based on metadata, without the need to load the assemblies for the parts.
For more information, see Managed Extensibility Framework. For a list of the MEF types, see the System.ComponentModel.Composition namespace.
Data
For more information, see What's New in ADO.NET.
Expression Trees
Expression trees are extended with new types that represent control flow, for example, LoopExpression and TryExpression. These new types are used by the dynamic language runtime (DLR) and not used by LINQ.
Communications
Windows Communication Foundation (WCF) provides the new features and enhancements described in the following sections.
Support for WS-Discovery
The Service Discovery feature enables client applications to dynamically discover service addresses at run time in an interoperable way using WS-Discovery. The WS-Discovery specification outlines the message-exchange patterns (MEPs) required for performing lightweight discovery of services, both by multicast (ad hoc) and unicast (using a network resource).
Standard Endpoints
Standard endpoints are pre-defined endpoints that have one or more of their properties (address, binding, contract) fixed. For example, all metadata exchange endpoints specify IMetadataExchange as their contract, so there is no need for a developer to have to specify the contract. Therefore, the standard MEX endpoint has a fixed IMetadataExchange contract.
Workflow Services
With the introduction of a set of messaging activities, it is easier than ever to implement workflows that send and receive data. These messaging activities enable you to model complex message exchange patterns that go outside the traditional send/receive or RPC-style method invocation.
Workflow
Windows Workflow Foundation (WF) in .NET Framework 4.0 changes several development paradigms from earlier versions. Workflows are now easier to create, execute, and maintain.
Workflow Activity Model
The activity is now the base unit of creating a workflow, instead of using the SequentialWorkflowActivity or StateMachineWorkflowActivity classes. The WorkflowElement class provides the base abstraction of workflow behavior. Activity authors implement WorkflowElement objects imperatively when they have to use the breadth of the runtime. The Activity class is a data-driven WorkflowElement object where activity authors express new behaviors declaratively in terms of other activity objects.
Richer Composite Activity Options
The Flowchart class is a powerful new control flow activity that enables authors to construct process flows more naturally. Procedural workflows benefit from new flow-control activities that model traditional flow-control structures, such as TryCatch and Switch.
Expanded Built-in Activity Library
New features of the activity library include the following:
Data access activities for interacting with ODBC data sources.
New flow control activities such as DoWhile, ForEach, and ParallelForEach.
Activities for interacting with PowerShell and SharePoint.
Enhanced Persistence and Unloading
Workflow state data can be explicitly persisted by using the Persist activity. A host can persist a WorkflowInstance without unloading it. A workflow can specify no-persist zones when working with data that cannot be persisted so that persistence is postponed until the no-persist zone exits.
Improved Ability to Extend WF Designer Experience
The new WF Designer is built on Windows Presentation Foundation (WPF) and provides an easier model to use when rehosting the WF Designer outside Visual Studio. It also provides easier mechanisms for creating custom activity designers. For more information, see Extending the Workflow Designer.
The new features and improvements are described in the following sections:
Programming Languages
Common Language Runtime (CLR)
Base Class Libraries
Networking
Web
Client
Data
Communications
Workflow
Common Language Runtime (CLR)
The following sections describe new features in security, parallel computing, performance and diagnostics, dynamic language runtime, and other CLR-related technologies.
Security
The .NET Framework 4.0 provides simplifications, improvements, and expanded capabilities in the security model. For more information, see Security Changes in the .NET Framework 4.
Parallel Computing
The .NET Framework 4.0 introduces a new programming model for writing multithreaded and asynchronous code that greatly simplifies the work of application and library developers. The new model enables developers to write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool. The new Parallel and Task classes, and other related types, support this new model. Parallel LINQ (PLINQ), which is a parallel implementation of LINQ to Objects, enables similar functionality through declarative syntax. For more information, see Parallel Programming in the .NET Framework.
Performance and Diagnostics
In addition to the following features, the .NET Framework 4.0 provides improvements in startup time, working set sizes, and faster performance for multithreaded applications.
ETW Events
You can now access the Event Tracing for Windows (ETW) events for diagnostic purposes to improve performance. For more information, see the following topics:
CLR ETW Events
Using Event Tracing for Windows to Log CLR Events
Performance Monitor (Perfmon.exe) now enables you to disambiguate multiple applications that use the same name and multiple versions of the common language runtime loaded by a single process. This requires a simple registry modification. For more information, see Performance Counters and In-Process Side-By-Side Applications.
Code Contracts
Code contracts let you specify contractual information that is not represented by a method's or type's signature alone. The new System.Diagnostics.Contracts namespace contains classes that provide a language-neutral way to express coding assumptions in the form of pre-conditions, post-conditions, and object invariants. The contracts improve testing with run-time checking, enable static contract verification, and documentation generation.
The applicable scenarios include the following:
Perform static bug finding, which enables some bugs to be found without executing the code.
Create guidance for automated testing tools to enhance test coverage.
Create a standard notation for code behavior, which provides more information for documentation.
Lazy Initialiation
With lazy initialization, the memory for an object is not allocated until it is needed. Lazy initialization can improve performance by spreading object allocations evenly across the lifetime of a program. You can enable lazy initialization for any custom type by wrapping the type inside a System..::.Lazy<(Of <(T>)>) class.
Dynamic Language Runtime
The dynamic language runtime (DLR) is a new runtime environment that adds a set of services for dynamic languages to the CLR. The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. To support the DLR, the new System.Dynamic namespace is added to the .NET Framework. In addition, several new classes that support the .NET Framework infrastructure are added to the System.Runtime.CompilerServices namespace. For more information, see Dynamic Language Runtime Overview.
In-Process Side-by-Side Execution
In-process side-by-side hosting enables an application to load and activate multiple versions of the common language runtime (CLR) in the same process. For example, you can run applications that are based on the .NET Framework 2.0 SP1 and applications that are based on .NET Framework 4.0 in the same process. Older components continue to use the same CLR version, and new components use the new CLR version. For more information, see Hosting Changes in the .NET Framework 4.
Interoperability
New interoperability features and improvements include the following:
You no longer have to use primary interop assemblies (PIAs). Compilers embed the parts of the interop assemblies that the add-ins actually use, and type safety is ensured by the common language runtime.
You can use the System.Runtime.InteropServices..::.ICustomQueryInterface interface to create a customized, managed code implementation of the IUnknown::QueryInterface method. Applications can use the customized implementation to return a specific interface (except IUnknown) for a particular interface ID.
Profiling
In the .NET Framework 4.0, you can attach profilers to a running process at any point, perform the requested profiling tasks, and then detach. For more information, see the [IClrProfiling::AttachProfiler]IClrProfiling Interface::AttachProfiler Method method.
Garbage Collection
The .NET Framework 4.0 provides background garbage collection; for more information, see the entry So, what’s new in the CLR 4.0 GC? in the CLR Garbage Collector blog.
Covariance and Contravariance
Several generic interfaces and delegates now support covariance and contravariance. For more information, see Covariance and Contravariance in the Common Language Runtime.
Base Class Libraries
The following sections describe new features in collections and data structures, exception handling, I/O, reflection, threading, and Windows registry.
Collections and Data Structures
Enhancements in this area include the new System.Numerics..::.BigInteger structure, the System.Collections.Generic..::.SortedSet<(Of <(T>)>) generic class, and tuples.
BigInteger
The new System.Numerics..::.BigInteger structure is an arbitrary-precision integer data type that supports all the standard integer operations, including bit manipulation. It can be used from any .NET Framework language. In addition, some of the new .NET Framework languages (such as F# and IronPython) have built-in support for this structure.
SortedSet Generic Class
The new System.Collections.Generic..::.SortedSet<(Of <(T>)>) class provides a self-balancing tree that maintains data in sorted order after insertions, deletions, and searches. This class implements the new System.Collections.Generic..::.ISet<(Of <(T>)>) interface.
The System.Collections.Generic..::.HashSet<(Of <(T>)>) class also implements the ISet<(Of <(T>)>) interface.
Tuples
A tuple is a simple generic data structure that holds an ordered set of items of heterogeneous types. Tuples are supported natively in languages such as F# and IronPython, but are also easy to use from any .NET Framework language such as C# and Visual Basic. The ..NET Framework 4.0 adds eight new generic tuple classes, and also a Tuple class that contains static factory methods for creating tuples.
Exceptions Handling
The .NET Framework 4.0 class library contains the new System.Runtime.ExceptionServices namespace, and adds the ability to handle corrupted state exceptions.
Corrupted State Exceptions
The CLR no longer delivers corrupted state exceptions that occur in the operating system to be handled by managed code, unless you apply the HandleProcessCorruptedStateExceptionsAttribute attribute to the method that handles the corrupted state exception.
Alternatively, you can add the following setting to an application's configuration file:
legacyCorruptedStateExceptionsPolicy=true
I/O
The key new features in I/O are efficient file enumerations, memory-mapped files, and improvements in isolated storage and compression.
File System Enumeration Improvements
New enumeration methods in the Directory and DirectoryInfo classes return IEnumerable<(Of <(T>)>) collections instead of arrays. These methods are more efficient than the array-based methods, because they do not have to allocate a (potentially large) array and you can access the first results immediately instead of waiting for the complete enumeration to occur.
There are also new methods in the static File class that read and write lines from files by using IEnumerable<(Of <(T>)>) collections. These methods are useful in LINQ scenarios where you may want to quickly and efficiently query the contents of a text file and write out the results to a log file without allocating any arrays.
Memory-Mapped Files
The new System.IO.MemoryMappedFiles namespace provides memory mapping functionality, which is available in Windows. You can use memory-mapped files to edit very large files and to create shared memory for inter-process communication. The new System.IO..::.UnmanagedMemoryAccessor class enables random access to unmanaged memory, similar to how System.IO..::.UnmanagedMemoryStream enables sequential access to unmanaged memory.
Isolated Storage Improvements
Partial-trust applications, such as Windows Presentation Framework (WPF) browser applications (XBAPs) and ClickOnce partial-trust applications, now have the same capabilities in the .NET Framework as they do in Silverlight. The default quota size is doubled, and applications can prompt the user to approve or reject a request to increase the quota. The System.IO.IsolatedStorage..::.IsolatedStorageFile class contains new members to manage the quota and to make working with files and directories easier.
Compression Improvements
The compression algorithms for the System.IO.Compression..::.DeflateStream and System.IO.Compression..::.GZipStream classes have improved so that data that is already compressed is no longer inflated. This results in much better compression ratios. Also, the 4-gigabyte size restriction for compressing streams has been removed.
Reflection
The .NET Framework 4.0 provides the capability to monitor the performance of your application domains.
Application Domain Resource Monitoring
Until now, there has been no way to determine whether a particular application domain is affecting other application domains, because the operating system APIs and tools, such as the Windows Task Manager, were precise only to the process level. Starting with the .NET Framework 4.0, you can get processor usage and memory usage estimates per application domain.
Application domain resource monitoring is available through the managed AppDomain class, native hosting APIs, and event tracing for Windows (ETW). When this feature has been enabled, it collects statistics on all application domains in the process for the life of the process.
For more information, see the
MonitoringIsEnabled
MonitoringSurvivedMemorySize
MonitoringSurvivedProcessMemorySize
MonitoringTotalAllocatedMemorySize
MonitoringTotalProcessorTime
64-bit View and Other Registry Improvements
Windows registry improvements include the following:
Ability to specify a 32-bit or 64-bit view of the registry with the Microsoft.Win32..::.RegistryView enumeration when you open base keys.
the new Microsoft.Win32..::.RegistryOptions enumeration, which lets you specify a volatile registry key that does not persist after the computer restarts.
Threading
General threading improvements include the following:
The new Monitor..::.Enter(Object, Boolean%) method overload takes a Boolean reference and atomically sets it to true only if the monitor is successfully entered.
You can use the Thread..::.Yield method to have the calling thread yield execution to another thread that is ready to run on the current processor.
The following sections describe new threading features.
Unified Model for Cancellation
The .NET Framework 4.0 provides a new unified model for cancellation of asynchronous operations. The new System.Threading..::.CancellationTokenSource class is used to create a CancellationToken that may be passed to any number of operations on multiple threads. By calling Cancel()()() on the token source object, the IsCancellationRequested property on the token is set to true and the token’s wait handle is signaled, at which time any registered actions with the token are invoked. Any object that has a reference to that token can monitor the value of that property and respond as appropriate.
Thread-Safe Collection Classes
The new System.Collections.Concurrent namespace introduces several new thread-safe collection classes that provide lock-free access to items whenever useful, and fine-grained locking when locks are appropriate. The use of these classes in multi-threaded scenarios should improve performance over collection types such as ArrayList, and List<(Of <(T>)>).
Synchronization Primitives
New synchronization primitives in the System.Threading namespace enable fine-grained concurrency and faster performance by avoiding expensive locking mechanisms. The Barrier class enables multiple threads to work on an algorithm cooperatively by providing a point at which each task can signal its arrival and then block until the other participants in the barrier have arrived. The CountdownEvent class simplifies fork and join scenarios by providing an easy rendezvous mechanism. The ManualResetEventSlim class is a lock-free synchronization primitive similar to the ManualResetEvent class. ManualResetEventSlim is lighter weight but can only be used for intra-process communication. The SemaphoreSlim class is a lightweight synchronization primitive that limits the number of threads that can access a resource or a pool of resources at the same time; it can be used only for intra-process communication. The SpinLock class is a mutual exclusion lock primitive that causes the thread that is trying to acquire the lock to wait in a loop, or spin, until the lock becomes available. The SpinWait class is a small, lightweight type that will spin for a time and eventually put the thread into a wait state if the spin count is exceeded.
Networking
Enhancements have been made that affect how integrated Windows authentication is handled by the HttpWebRequest, HttpListener, SmtpClient, SslStream, NegotiateStream, and related classes in the System.Net and related namespaces. Support was added for extended protection to enhance security. The changes to support extended protection are available only for applications on Windows 7. The extended protection features are not available on earlier versions of Windows. For more information, seeIntegrated Windows Authentication with Extended Protection.
Web
The following sections describe new features in ASP.NET core services, Web Forms, Dynamic Data, and Visual Web Developer.
ASP.NET Core Services
ASP.NET introduces several features that improve core ASP.NET services, Web Forms, Dynamic Data, and Visual Web Developer. For more information, see What’s New in ASP.NET and Web Development.
ASP.NET Web Forms
Web Forms has been a core feature in ASP.NET since the release of ASP.NET 1.0. Many enhancements have been made in this area for ASP.NET 4, including the following:
The ability to set meta tags.
More control over view state.
Easier ways to work with browser capabilities.
Support for using ASP.NET routing with Web Forms.
More control over generated IDs.
The ability to persist selected rows in data controls.
More control over rendered HTML in the FormView and ListView controls.
Filtering support for data source controls.
Dynamic Data
For ASP.NET 4, Dynamic Data has been enhanced to give developers even more power for quickly building data-driven Web sites. This includes the following:
Automatic validation that is based on constraints defined in the data model.
The ability to easily change the markup that is generated for fields in the GridView and DetailsView controls by using field templates that are part of your Dynamic Data project.
Visual Web Developer Enhancements
The Web page designer in Visual Studio 2010 has been enhanced for better CSS compatibility, includes additional support for HTML and ASP.NET markup code examples, and features a redesigned version of IntelliSense for JScript. In addition, two new deployment features called Web packaging and One-Click Publish make deploying Web applications easier.
Client
The following sections describe new features in Windows Presentation Foundation (WPF) and Managed Extensibility Framework (MEF).
Windows Presentation Foundation
In the .NET Framework 4.0, Windows Presentation Foundation (WPF) contains changes and improvements in many areas. This includes controls, graphics, and XAML.
For more information, see What's New in Windows Presentation Foundation Version 4.
Managed Extensibility Framework
The Managed Extensibility Framework (MEF) is a new library in the .NET Framework 4.0 that enables you to build extensible and composable applications. MEF enables application developers to specify points where an application can be extended, expose services to offer to other extensible applications, and create parts for consumption by extensible applications. It also enables easy discoverability of available parts based on metadata, without the need to load the assemblies for the parts.
For more information, see Managed Extensibility Framework. For a list of the MEF types, see the System.ComponentModel.Composition namespace.
Data
For more information, see What's New in ADO.NET.
Expression Trees
Expression trees are extended with new types that represent control flow, for example, LoopExpression and TryExpression. These new types are used by the dynamic language runtime (DLR) and not used by LINQ.
Communications
Windows Communication Foundation (WCF) provides the new features and enhancements described in the following sections.
Support for WS-Discovery
The Service Discovery feature enables client applications to dynamically discover service addresses at run time in an interoperable way using WS-Discovery. The WS-Discovery specification outlines the message-exchange patterns (MEPs) required for performing lightweight discovery of services, both by multicast (ad hoc) and unicast (using a network resource).
Standard Endpoints
Standard endpoints are pre-defined endpoints that have one or more of their properties (address, binding, contract) fixed. For example, all metadata exchange endpoints specify IMetadataExchange as their contract, so there is no need for a developer to have to specify the contract. Therefore, the standard MEX endpoint has a fixed IMetadataExchange contract.
Workflow Services
With the introduction of a set of messaging activities, it is easier than ever to implement workflows that send and receive data. These messaging activities enable you to model complex message exchange patterns that go outside the traditional send/receive or RPC-style method invocation.
Workflow
Windows Workflow Foundation (WF) in .NET Framework 4.0 changes several development paradigms from earlier versions. Workflows are now easier to create, execute, and maintain.
Workflow Activity Model
The activity is now the base unit of creating a workflow, instead of using the SequentialWorkflowActivity or StateMachineWorkflowActivity classes. The WorkflowElement class provides the base abstraction of workflow behavior. Activity authors implement WorkflowElement objects imperatively when they have to use the breadth of the runtime. The Activity class is a data-driven WorkflowElement object where activity authors express new behaviors declaratively in terms of other activity objects.
Richer Composite Activity Options
The Flowchart class is a powerful new control flow activity that enables authors to construct process flows more naturally. Procedural workflows benefit from new flow-control activities that model traditional flow-control structures, such as TryCatch and Switch.
Expanded Built-in Activity Library
New features of the activity library include the following:
Data access activities for interacting with ODBC data sources.
New flow control activities such as DoWhile, ForEach, and ParallelForEach.
Activities for interacting with PowerShell and SharePoint.
Enhanced Persistence and Unloading
Workflow state data can be explicitly persisted by using the Persist activity. A host can persist a WorkflowInstance without unloading it. A workflow can specify no-persist zones when working with data that cannot be persisted so that persistence is postponed until the no-persist zone exits.
Improved Ability to Extend WF Designer Experience
The new WF Designer is built on Windows Presentation Foundation (WPF) and provides an easier model to use when rehosting the WF Designer outside Visual Studio. It also provides easier mechanisms for creating custom activity designers. For more information, see Extending the Workflow Designer.
New Features in vs 2008 for professional
22 New Features of Visual Studio 2008 for .NET Professionals
1. LINQ Support
LINQ essentially is the composition of many standard query operators that allow you to work with data in a more intuitive way regardless.
The benefits of using LINQ are significant – Compile time checking C# language queries, and the ability to debug step by step through queries.
2. Expression Blend Support
Expression blend is XAML generator tool for silverlight applications. You can install Expression blend as an embedded plug-in to Visual Studio 2008. By this you can get extensive web designer and JavaScript tool.
3. Windows Presentation Foundation
WPF provides you an extensive graphic functionality you never seen these before. Visual Studio 2008 contains plenty of WPF Windows Presentation Foundation Library templates. By this a visual developer who is new to .NET, C# and VB.NET can easily develop the 2D and 3D graphic applications.
Visual Studio 2008 provides free game development library kits for games developers. currently this game development kits are available for C++ and also 2D/3D Dark Matter one image and sounds sets.
4. VS 2008 Multi-Targeting Support
Earlier you were not able to working with .NET 1.1 applications directly in visual studio 2005. Now in Visual studio 2008 you are able to create, run, debug the .NET 2.0, .NET 3.0 and .NET 3.5 applications. You can also deploy .NET 2.0 applications in the machines which contains only .NET 2.0 not .NET 3.x.
5. AJAX support for ASP.NET
Previously developer has to install AJAX control library separately that does not come from VS, but now if you install Visual Studio 2008, you can built-in AJAX control library. This Ajax Library contains plenty of rich AJAX controls like Menu, TreeView, webparts and also these components support JSON and VS 2008 contains in built ASP.NET AJAX Control Extenders.
6. JavaScript Debugging Support
Since starting of web development all the developers got frustration with solving javascript errors. Debugging the error in javascript is very difficult. Now Visual Studio 2008 makes it is simpler with javascript debugging. You can set break points and run the javaScript step by step and you can watch the local variables when you were debugging the javascript and solution explorer provides javascript document navigation support.
7. Nested Master Page Support
Already Visual Studio 2005 supports nested master pages concept with .NET 2.0, but the problem with this Visual Studio 2005 that pages based on nested masters can't be edited using WYSIWYG web designer. But now in VS 2008 you can even edit the nested master pages.
8. LINQ Intellisense and Javascript Intellisense support for silverlight applications
Most happy part for .NET developers is Visual Studio 2008 contains intellisense support for javascript. Javascript Intellisense makes developers life easy when writing client side validation, AJAX applications and also when writing Silverlight applications
Intellisense Support: When we are writing the LINQ Query VS provides LINQ query syntax as tool tips.
9. Organize Imports or Usings: We have Organize Imports feature already in Eclipse. SInce many days I have been waiting for this feature even in VS. Now VS contains Organize Imports feature which removes unnecessary namespaces which you have imported. You can select all the namespaces and right click on it, then you can get context menu with Organize imports options like "Remove Unused Usings", "Sort Usings", "Remove and Sort". Refactoring support for new .NET 3.x features like Anonymous types, Extension Methods, Lambda Expressions.
10. Intellisense Filtering: Earlier in VS 2005 when we were typing with intellisense box all the items were being displayed. For example If we type the letter 'K' then intellisense takes you to the items starts with 'K' but also all other items will be presented in intellisense box. Now in VS 2008 if you press 'K' only the items starts with 'K' will be filtered and displayed.
11. Intellisense Box display position
Earlier in some cases when you were typing the an object name and pressing . (period) then intellisense was being displayed in the position of the object which you have typed. Here the code which we type will go back to the dropdown, in this case sometimes programmer may disturb to what he was typing. Now in VS 2008 If you hold the Ctrl key while the intellisense is dropping down then intellisense box will become semi-transparent mode.
12. Visual Studio 2008 Split View
VS 205 has a feature show both design and source code in single window. but both the windows tiles horizontally. In VS 2008 we can configure this split view feature to vertically, this allows developers to use maximum screen on laptops and wide-screen monitors.
Here one of the good feature is if you select any HTML or ASP markup text in source window automatically corresponding item will be selected in design window.
13. HTML JavaScript warnings, not as errors: VS 2005 mixes HTML errors and C# and VB.NET errors and shows in one window. Now VS 2008 separates this and shows javascript and HTML errors as warnings. But this is configurable feature.
14. Debugging .NET Framework Library Source Code:
Now in VS 2008 you can debug the source code of .NET Framework Library methods. Lets say If you want to debug the DataBind() method of DataGrid control you can place a debugging point over there and continue with debug the source code of DataBind() method.
15. In built Silverlight Library
Earlier we used to install silverlight SDK separately, Now in VS 2008 it is inbuilt, with this you can create, debug and deploy the silverlight applications.
16. Visual Studio LINQ Designer
Already you know in VS 2005 we have inbuilt SQL Server IDE feature. by this you no need to use any other tools like SQL Server Query Analyzer and SQL Server Enterprise Manger. You have directly database explorer by this you can create connections to your database and you can view the tables and stored procedures in VS IDE itself. But now in VS 2008 it has View Designer window capability with LINQ-to-SQL.
17. Inbuilt C++ SDK
Earlier It was so difficult to download and configure the C++ SDK Libraries and tools for developing windows based applications. Now it is inbuilt with VS 2008 and configurable
18. Multilingual User Interface Architecture - MUI
MUI is an architecture contains packages from Microsoft Windows and Microsoft Office libraries. This supports the user to change the text language display as he wish.
Visual Studio is now in English, Spanish, French, German, Italian, Chinese Simplified, Chinese Traditional, Japanese, and Korean. Over the next couple of months. Microsoft is reengineering the MUI which supports nine local languages then you can even view Visual studio in other 9 local languages.
19. Microsoft Popfly Support
Microsoft Popfly explorer is an add-on to VS 2008, by this directly you can deploy or hosting the Silverlight applications and Marshup objects
20. Free Tools and Resources
People may feel that I am a promoter to Visual Studio 2008 as a salesman, but we get plenty of free resources and free tools with Visual Studio 2008.
Visual Studio 2008 Trial
101 LINQ Samples
Free .NET 3.5 control libraries with free sample programs,
You can get plenty of free video training tutorials from Microsoft BDLC - Beginner Developer Learning Center,
C++ games development library,
Microsoft has provided lot of e-Books,
P2P library and
Microsoft is providing Coding4Fun sample program kit.
Visual Studio Registration Discounts: If you register the Visual Studio you get Free Control Libraries, Books, Images, and Discounts.
Download Visual Studio 2008 free trial
21. We can use for Commercial
Earlier you were spending lot of money to host your .NET applications for commercial use. Now you no need to worry Now Microsoft is providing you to host your application free on Popfly for web pages and also visual studio express projects.
1. LINQ Support
LINQ essentially is the composition of many standard query operators that allow you to work with data in a more intuitive way regardless.
The benefits of using LINQ are significant – Compile time checking C# language queries, and the ability to debug step by step through queries.
2. Expression Blend Support
Expression blend is XAML generator tool for silverlight applications. You can install Expression blend as an embedded plug-in to Visual Studio 2008. By this you can get extensive web designer and JavaScript tool.
3. Windows Presentation Foundation
WPF provides you an extensive graphic functionality you never seen these before. Visual Studio 2008 contains plenty of WPF Windows Presentation Foundation Library templates. By this a visual developer who is new to .NET, C# and VB.NET can easily develop the 2D and 3D graphic applications.
Visual Studio 2008 provides free game development library kits for games developers. currently this game development kits are available for C++ and also 2D/3D Dark Matter one image and sounds sets.
4. VS 2008 Multi-Targeting Support
Earlier you were not able to working with .NET 1.1 applications directly in visual studio 2005. Now in Visual studio 2008 you are able to create, run, debug the .NET 2.0, .NET 3.0 and .NET 3.5 applications. You can also deploy .NET 2.0 applications in the machines which contains only .NET 2.0 not .NET 3.x.
5. AJAX support for ASP.NET
Previously developer has to install AJAX control library separately that does not come from VS, but now if you install Visual Studio 2008, you can built-in AJAX control library. This Ajax Library contains plenty of rich AJAX controls like Menu, TreeView, webparts and also these components support JSON and VS 2008 contains in built ASP.NET AJAX Control Extenders.
6. JavaScript Debugging Support
Since starting of web development all the developers got frustration with solving javascript errors. Debugging the error in javascript is very difficult. Now Visual Studio 2008 makes it is simpler with javascript debugging. You can set break points and run the javaScript step by step and you can watch the local variables when you were debugging the javascript and solution explorer provides javascript document navigation support.
7. Nested Master Page Support
Already Visual Studio 2005 supports nested master pages concept with .NET 2.0, but the problem with this Visual Studio 2005 that pages based on nested masters can't be edited using WYSIWYG web designer. But now in VS 2008 you can even edit the nested master pages.
8. LINQ Intellisense and Javascript Intellisense support for silverlight applications
Most happy part for .NET developers is Visual Studio 2008 contains intellisense support for javascript. Javascript Intellisense makes developers life easy when writing client side validation, AJAX applications and also when writing Silverlight applications
Intellisense Support: When we are writing the LINQ Query VS provides LINQ query syntax as tool tips.
9. Organize Imports or Usings: We have Organize Imports feature already in Eclipse. SInce many days I have been waiting for this feature even in VS. Now VS contains Organize Imports feature which removes unnecessary namespaces which you have imported. You can select all the namespaces and right click on it, then you can get context menu with Organize imports options like "Remove Unused Usings", "Sort Usings", "Remove and Sort". Refactoring support for new .NET 3.x features like Anonymous types, Extension Methods, Lambda Expressions.
10. Intellisense Filtering: Earlier in VS 2005 when we were typing with intellisense box all the items were being displayed. For example If we type the letter 'K' then intellisense takes you to the items starts with 'K' but also all other items will be presented in intellisense box. Now in VS 2008 if you press 'K' only the items starts with 'K' will be filtered and displayed.
11. Intellisense Box display position
Earlier in some cases when you were typing the an object name and pressing . (period) then intellisense was being displayed in the position of the object which you have typed. Here the code which we type will go back to the dropdown, in this case sometimes programmer may disturb to what he was typing. Now in VS 2008 If you hold the Ctrl key while the intellisense is dropping down then intellisense box will become semi-transparent mode.
12. Visual Studio 2008 Split View
VS 205 has a feature show both design and source code in single window. but both the windows tiles horizontally. In VS 2008 we can configure this split view feature to vertically, this allows developers to use maximum screen on laptops and wide-screen monitors.
Here one of the good feature is if you select any HTML or ASP markup text in source window automatically corresponding item will be selected in design window.
13. HTML JavaScript warnings, not as errors: VS 2005 mixes HTML errors and C# and VB.NET errors and shows in one window. Now VS 2008 separates this and shows javascript and HTML errors as warnings. But this is configurable feature.
14. Debugging .NET Framework Library Source Code:
Now in VS 2008 you can debug the source code of .NET Framework Library methods. Lets say If you want to debug the DataBind() method of DataGrid control you can place a debugging point over there and continue with debug the source code of DataBind() method.
15. In built Silverlight Library
Earlier we used to install silverlight SDK separately, Now in VS 2008 it is inbuilt, with this you can create, debug and deploy the silverlight applications.
16. Visual Studio LINQ Designer
Already you know in VS 2005 we have inbuilt SQL Server IDE feature. by this you no need to use any other tools like SQL Server Query Analyzer and SQL Server Enterprise Manger. You have directly database explorer by this you can create connections to your database and you can view the tables and stored procedures in VS IDE itself. But now in VS 2008 it has View Designer window capability with LINQ-to-SQL.
17. Inbuilt C++ SDK
Earlier It was so difficult to download and configure the C++ SDK Libraries and tools for developing windows based applications. Now it is inbuilt with VS 2008 and configurable
18. Multilingual User Interface Architecture - MUI
MUI is an architecture contains packages from Microsoft Windows and Microsoft Office libraries. This supports the user to change the text language display as he wish.
Visual Studio is now in English, Spanish, French, German, Italian, Chinese Simplified, Chinese Traditional, Japanese, and Korean. Over the next couple of months. Microsoft is reengineering the MUI which supports nine local languages then you can even view Visual studio in other 9 local languages.
19. Microsoft Popfly Support
Microsoft Popfly explorer is an add-on to VS 2008, by this directly you can deploy or hosting the Silverlight applications and Marshup objects
20. Free Tools and Resources
People may feel that I am a promoter to Visual Studio 2008 as a salesman, but we get plenty of free resources and free tools with Visual Studio 2008.
Visual Studio 2008 Trial
101 LINQ Samples
Free .NET 3.5 control libraries with free sample programs,
You can get plenty of free video training tutorials from Microsoft BDLC - Beginner Developer Learning Center,
C++ games development library,
Microsoft has provided lot of e-Books,
P2P library and
Microsoft is providing Coding4Fun sample program kit.
Visual Studio Registration Discounts: If you register the Visual Studio you get Free Control Libraries, Books, Images, and Discounts.
Download Visual Studio 2008 free trial
21. We can use for Commercial
Earlier you were spending lot of money to host your .NET applications for commercial use. Now you no need to worry Now Microsoft is providing you to host your application free on Popfly for web pages and also visual studio express projects.
features of Silverlight 4?
What are the features of Silverlight 4?
Silverlight 4 delivers a full suite of powerful features to application developers, bringing innovative platform capabilities to browser-based experiences. Silverlight provides an ideal platform for developing and deploying modern business applications for both internal and end-user applications on both sides of the firewall
Enabling business application development. Silverlight 4 affirms its position as the natural choice for building business applications on the Web:
What’s new for application developers
Comprehensive printing support now enables the creation of a virtual print view, enabling applications to deliver print-friendly documents.
A full set of controls with more than 60 customizable, skinnable components makes it easy to build forms that can be sorted, resized and validated. New controls include RichTextArea with hyperlinks, images and editing.
Localization enhancements with bidirectional text, right-to-left support and complex scripts such as Arabic, Hebrew and Thai and 30 new languages.
The Microsoft .NET Framework Common Language Runtime (CLR) now enables the same compiled code to be run both on the server and the client, reducing development time and testing resources.
Enhanced databinding support reduces the amount of code needed to work with customized data for display.
Managed Extensibility Framework supports building completely modular applications, allowing for fast startup and download, efficient development and testing, as well as agile customization and servicing.
Windows Communication Foundation RIA Services introduces enterprise class networking and data access, allowing applications to work with any source of data and any server.
Extensive tooling support for Silverlight, new in Visual Studio 2010:
Fully editable design surface for drawing out controls and layouts
Rich property grid and new editors for values
Drag and drop support for databinding and automatically creating bound controls such as listbox and datagrid
New datasources window and picker
Easy-to-pick styles and resources to make a good-looking application based on designer resources built in Expression Blend
Built-in project support for Silverlight applications
Editor with full IntelliSense for XAML and C# and Visual Basic languages
Empowering richer experiences. Silverlight 4 introduces additional capabilities that enable developers to create richer, more appealing, high-performance interactive and innovative media experiences:
Enhanced animation capabilities allow for more dynamic, interactive presentation of data in lists.
Webcam and microphone support allow sharing of video and audio in applications such as chat and customer service.
Audio and video local recording capabilities capture RAW video without requiring server interaction, allowing new scenarios such as capturing voice or video to send in e-mail, or allowing the recording to be edited locally before saving.
Copy/paste and drag-and-drop make it easy to bring photos, text and other data into your application.
New features such as right-click and mouse wheel scrolling enable developers to add conventional desktop interaction models.
Silverlight 4 runs across all platforms and major browsers.
Silverlight 4 applications start quicker and run 200 percent faster than the equivalent Silverlight 3 applications with performance optimizations.
Multitouch support enables a range of gestures and touch interactions to be integrated into user experiences.
Multicast networking enables enterprises to lower the cost of streaming broadcast events such as company meetings and training, with seamless interoperability with existing Windows Media Services streaming infrastructure.
Content protection now available for H.264 media through Silverlight DRM powered by PlayReady.
Output protection for audio/video streams allowing content owners or distributors to ensure protected content is only viewed through a secure video connection.
Official support of the Google Chrome browser
Hardware acceleration for Deep Zoom
XAP signing and verification to ensure application integrity
Moving beyond the browser. Silverlight 4 extends out-of-browser capabilities pioneered in Silverlight 3 that enable a Web presence to establish closer, more persistent relationships with customers without any additional runtime download or the need to write applications in a different way.
For sandboxed applications
Developers can place HTML within their application, enabling much tighter integration with content from Web servers such as e-mail, help and reports.
Silverlight 4 provides support for desktop pop-up notification windows to easily provide real-time information and feedback to users using a common user interface metaphor.
Offline DRM extends the existing Silverlight DRM powered by PlayReady technology to work in a disconnected state, enabling users to view content and engage with a Silverlight application where and when they want. Protected content can be delivered with an embedded license so that users can go offline immediately and start enjoying their content.
Silverlight 4 offers full control over window settings such as start position and size to ensure applications have maximum usability and flexibility.
For trusted applications
Users can read and write files to their My Documents, My Music, My Pictures and My Videos folder (or equivalent for non-Windows platforms), enabling applications to make local copies of reports and media files.
COM automation enables access to devices and other system capabilities such as a Universal Serial Bus security card reader.
Users can access other desktop programs such as Microsoft Office Excel to create a report.
Group policy objects allow organizations to manage which applications are trusted.
Comprehensive keyboard support in full-screen out-of-browser mode enhances kiosk and media applications.
Enhancements to networking allow cross-domain access without a security policy file.
What are the features of Silverlight for Windows Phone 7?
Silverlight for Windows Phone will support core Silverlight features while optimizing for capabilities specific to the Windows Phone 7. Feature highlights include the following:
Hardware-accelerated video with multicodec digital rights management (DRM) and Internet Information Services Smooth Streaming support
Vector and bitmap graphics with perspective 3-D
Multitouch support with Accelerometer, an intuitive control that responds to motion
Deep Zoom support for rich reading experiences
Camera and microphone support
Notification Service for pushing information to the phone, regardless of whether or not an application is running
Integration with the core Windows Phone 7 Series experience features such as hubs
An overview of developing for Windows Phone can be found here and more information about Silverlight on Windows Phone can be found here.
What is Microsoft Silverlight?
What is Microsoft Silverlight?
Silverlight is a powerful development platform for creating engaging, interactive applications for the Web, desktop, and mobile devices. Silverlight is a free plug-in powered by the .NET framework that is compatible across multiple browsers, devices and operating systems to bring a new level of interactivity wherever the Web works. With support for advanced data integration, multithreading, HD video using IIS Smooth Streaming, and built in content protection, Silverlight enables online and offline applications for a broad range of business and consumer scenarios.
Is Silverlight free?
Yes, Microsoft has made the Silverlight browser plug-in freely available for all supported platforms and browsers.
Which platforms and browsers will Silverlight 3 support?
Silverlight is supported by all major browsers on both Mac OS X and Windows, and with Moonlight on Linux as well. Particular care is being taken to account for differences in platform and browser capabilities to ensure a consistent experience including experiences on Internet Explorer 6, 7 8, Firefox2 and 3, Safari 3 and 4, and now Google Chrome.
Will I need more memory, a faster processor, or a better Graphics Processing Unit (GPU)?
Microsoft designed Silverlight with the ability to deliver high-fidelity experiences on the broadest set of system configurations. Some features, such as HD video, may benefit from the power contained in newer personal computers.
How do I verify Silverlight is installed?
Verify your installation by visiting the Silverlight installation page.
How can I deploy Silverlight on my corporate network?
The Silverlight Deployment Guide thoroughly details all the steps for rolling out Silverlight on a corporate network.
Developing Silverlight Applications
Where can I download Silverlight and the associated Software Development Kits (SDKs)?
The Silverlight installer and tools for Designers and Developers can be found on the Resources page. The Silverlight community site is also a great resource for developers to find additional resources and get started.
Where can I go to connect with other Silverlight developers to ask questions?
For Silverlight-related forums, blogs, and community resources visit the Silverlight Support and Community page
System Requirements
What are the system requirements for Silverlight 3?
The system requirements for Microsoft Silverlight and associated technologies are listed below.
Windows
Operating System: Windows 7,Windows Vista; Windows XP Service Pack 2
Intel® Pentium® III 450MHz or faster processor (or equivalent)
128MB of RAM
Mac OS
Operating System: Apple Mac OS X 10.4.8 or above
Intel Core™ Duo 1.83GHz or faster processor
128MB of RAM
Linux
For the system requirements, please refer to the Mono Project's Moonlight Web site.
Links
Where can I go to learn more about Silverlight?
As you review Microsoft Silverlight, please feel free to consult any of the many additional resources provided. More information can be found at the following locations:
Microsoft Silverlight Home Page
Microsoft Expression Home Page
MSDN Developer Center
Microsoft Silverlight Community
Silverlight 4 delivers a full suite of powerful features to application developers, bringing innovative platform capabilities to browser-based experiences. Silverlight provides an ideal platform for developing and deploying modern business applications for both internal and end-user applications on both sides of the firewall
Enabling business application development. Silverlight 4 affirms its position as the natural choice for building business applications on the Web:
What’s new for application developers
Comprehensive printing support now enables the creation of a virtual print view, enabling applications to deliver print-friendly documents.
A full set of controls with more than 60 customizable, skinnable components makes it easy to build forms that can be sorted, resized and validated. New controls include RichTextArea with hyperlinks, images and editing.
Localization enhancements with bidirectional text, right-to-left support and complex scripts such as Arabic, Hebrew and Thai and 30 new languages.
The Microsoft .NET Framework Common Language Runtime (CLR) now enables the same compiled code to be run both on the server and the client, reducing development time and testing resources.
Enhanced databinding support reduces the amount of code needed to work with customized data for display.
Managed Extensibility Framework supports building completely modular applications, allowing for fast startup and download, efficient development and testing, as well as agile customization and servicing.
Windows Communication Foundation RIA Services introduces enterprise class networking and data access, allowing applications to work with any source of data and any server.
Extensive tooling support for Silverlight, new in Visual Studio 2010:
Fully editable design surface for drawing out controls and layouts
Rich property grid and new editors for values
Drag and drop support for databinding and automatically creating bound controls such as listbox and datagrid
New datasources window and picker
Easy-to-pick styles and resources to make a good-looking application based on designer resources built in Expression Blend
Built-in project support for Silverlight applications
Editor with full IntelliSense for XAML and C# and Visual Basic languages
Empowering richer experiences. Silverlight 4 introduces additional capabilities that enable developers to create richer, more appealing, high-performance interactive and innovative media experiences:
Enhanced animation capabilities allow for more dynamic, interactive presentation of data in lists.
Webcam and microphone support allow sharing of video and audio in applications such as chat and customer service.
Audio and video local recording capabilities capture RAW video without requiring server interaction, allowing new scenarios such as capturing voice or video to send in e-mail, or allowing the recording to be edited locally before saving.
Copy/paste and drag-and-drop make it easy to bring photos, text and other data into your application.
New features such as right-click and mouse wheel scrolling enable developers to add conventional desktop interaction models.
Silverlight 4 runs across all platforms and major browsers.
Silverlight 4 applications start quicker and run 200 percent faster than the equivalent Silverlight 3 applications with performance optimizations.
Multitouch support enables a range of gestures and touch interactions to be integrated into user experiences.
Multicast networking enables enterprises to lower the cost of streaming broadcast events such as company meetings and training, with seamless interoperability with existing Windows Media Services streaming infrastructure.
Content protection now available for H.264 media through Silverlight DRM powered by PlayReady.
Output protection for audio/video streams allowing content owners or distributors to ensure protected content is only viewed through a secure video connection.
Official support of the Google Chrome browser
Hardware acceleration for Deep Zoom
XAP signing and verification to ensure application integrity
Moving beyond the browser. Silverlight 4 extends out-of-browser capabilities pioneered in Silverlight 3 that enable a Web presence to establish closer, more persistent relationships with customers without any additional runtime download or the need to write applications in a different way.
For sandboxed applications
Developers can place HTML within their application, enabling much tighter integration with content from Web servers such as e-mail, help and reports.
Silverlight 4 provides support for desktop pop-up notification windows to easily provide real-time information and feedback to users using a common user interface metaphor.
Offline DRM extends the existing Silverlight DRM powered by PlayReady technology to work in a disconnected state, enabling users to view content and engage with a Silverlight application where and when they want. Protected content can be delivered with an embedded license so that users can go offline immediately and start enjoying their content.
Silverlight 4 offers full control over window settings such as start position and size to ensure applications have maximum usability and flexibility.
For trusted applications
Users can read and write files to their My Documents, My Music, My Pictures and My Videos folder (or equivalent for non-Windows platforms), enabling applications to make local copies of reports and media files.
COM automation enables access to devices and other system capabilities such as a Universal Serial Bus security card reader.
Users can access other desktop programs such as Microsoft Office Excel to create a report.
Group policy objects allow organizations to manage which applications are trusted.
Comprehensive keyboard support in full-screen out-of-browser mode enhances kiosk and media applications.
Enhancements to networking allow cross-domain access without a security policy file.
What are the features of Silverlight for Windows Phone 7?
Silverlight for Windows Phone will support core Silverlight features while optimizing for capabilities specific to the Windows Phone 7. Feature highlights include the following:
Hardware-accelerated video with multicodec digital rights management (DRM) and Internet Information Services Smooth Streaming support
Vector and bitmap graphics with perspective 3-D
Multitouch support with Accelerometer, an intuitive control that responds to motion
Deep Zoom support for rich reading experiences
Camera and microphone support
Notification Service for pushing information to the phone, regardless of whether or not an application is running
Integration with the core Windows Phone 7 Series experience features such as hubs
An overview of developing for Windows Phone can be found here and more information about Silverlight on Windows Phone can be found here.
What is Microsoft Silverlight?
What is Microsoft Silverlight?
Silverlight is a powerful development platform for creating engaging, interactive applications for the Web, desktop, and mobile devices. Silverlight is a free plug-in powered by the .NET framework that is compatible across multiple browsers, devices and operating systems to bring a new level of interactivity wherever the Web works. With support for advanced data integration, multithreading, HD video using IIS Smooth Streaming, and built in content protection, Silverlight enables online and offline applications for a broad range of business and consumer scenarios.
Is Silverlight free?
Yes, Microsoft has made the Silverlight browser plug-in freely available for all supported platforms and browsers.
Which platforms and browsers will Silverlight 3 support?
Silverlight is supported by all major browsers on both Mac OS X and Windows, and with Moonlight on Linux as well. Particular care is being taken to account for differences in platform and browser capabilities to ensure a consistent experience including experiences on Internet Explorer 6, 7 8, Firefox2 and 3, Safari 3 and 4, and now Google Chrome.
Will I need more memory, a faster processor, or a better Graphics Processing Unit (GPU)?
Microsoft designed Silverlight with the ability to deliver high-fidelity experiences on the broadest set of system configurations. Some features, such as HD video, may benefit from the power contained in newer personal computers.
How do I verify Silverlight is installed?
Verify your installation by visiting the Silverlight installation page.
How can I deploy Silverlight on my corporate network?
The Silverlight Deployment Guide thoroughly details all the steps for rolling out Silverlight on a corporate network.
Developing Silverlight Applications
Where can I download Silverlight and the associated Software Development Kits (SDKs)?
The Silverlight installer and tools for Designers and Developers can be found on the Resources page. The Silverlight community site is also a great resource for developers to find additional resources and get started.
Where can I go to connect with other Silverlight developers to ask questions?
For Silverlight-related forums, blogs, and community resources visit the Silverlight Support and Community page
System Requirements
What are the system requirements for Silverlight 3?
The system requirements for Microsoft Silverlight and associated technologies are listed below.
Windows
Operating System: Windows 7,Windows Vista; Windows XP Service Pack 2
Intel® Pentium® III 450MHz or faster processor (or equivalent)
128MB of RAM
Mac OS
Operating System: Apple Mac OS X 10.4.8 or above
Intel Core™ Duo 1.83GHz or faster processor
128MB of RAM
Linux
For the system requirements, please refer to the Mono Project's Moonlight Web site.
Links
Where can I go to learn more about Silverlight?
As you review Microsoft Silverlight, please feel free to consult any of the many additional resources provided. More information can be found at the following locations:
Microsoft Silverlight Home Page
Microsoft Expression Home Page
MSDN Developer Center
Microsoft Silverlight Community
Software Requirements Specification
Software Requirements Specification
Release Information
Project:
PROJECTNAME
Internal Release Number:
X.Y.Z
Attached worksheets:
SRS > Use case suite
SRS > Feature set
Related Documents:
Project proposal > User needs
LINKS TO RELEVANT STANDARDS
LINKS TO OTHER DOCUMENTS
Glossary
Process impact: The SRS precisely defines the software product that will be built. Decisions made in writing the SRS are based on information in the project proposal and user needs documents. The SRS sets requirements that must be satisfied by the system design. The SRS is verified and validated by activities outlined in the QA plan.
Introduction
TODO: Provide a brief overview of this release of the product. You can copy text from the project proposal, paste it here, and shorten it.
PARAGRAPH
PARAGRAPH
For more information, see the project proposal.
Use Cases
ONE PARAGRAPH OVERVIEW
Details:
Actors are described in the user needs document.
The use case suite lists all use cases in an organized way.
Functional Requirements
ONE PARAGRAPH OVERVIEW
Details:
The feature set lists all features in an organized way.
Non-Functional Requirements
TODO: Describe the non-functional requirements for this release. Some examples are provided below.
What are the usability requirements?
Our main criteria for making the system usable is the difficulty of performing each high-frequency use case. Difficulty depends on the number of steps, the knowledge that the user must have at each step, the decisions that the user must make at each step, and the mechanics of each step (e.g., typing a book title exactly is hard, clicking on a title in a list is easy).
The user interface should be as familiar as possible to users who have used other web applications and Windows desktop applications. E.g., we will follow the UI guidelines for naming menus, buttons, and dialog boxes whenever possible.
PARAGRAPH
Details:
Government customers will demand section508 compliance
Support learnability with principles of Instructive Interaction
The customer wants extensive on-line help, but is not demanding a printed manual.
What are the reliability and up-time requirements?
PARAGRAPH
PARAGRAPH
Details:
DETAIL
DETAIL
DETAIL
What are the safety requirements?
PARAGRAPH
PARAGRAPH
Details:
DETAIL
DETAIL
DETAIL
What are the security requirements?
Access will be controlled with usernames and passwords.
Only administrator users will have access to administrative functions, average users will not.
Details:
Passwords must be 4-14 characters long
We will not use encrypted communications (SSL) for this website
DETAIL
What are the performance and scalability requirements requirements?
PARAGRAPH
PARAGRAPH
Details:
DETAIL
DETAIL
DETAIL
What are the maintainability and upgradability requirements?
Maintainability is our ability to make changes to the product over time. We need strong maintainability in order to retain our early customers. We will address this by anticipating several types of change, and by carefully documenting our design and implementation.
Upgradability is our ability to cost-effectively deploy new versions of the product to customers with minimal downtime or disruption. A key feature supporting this goal is automatic download of patches and upgrade of the end-user's machine. Also, we shall use data file formats that include enough meta-data to allow us to reliably transform existing customer data during an upgrade.
Details:
DETAIL
DETAIL
DETAIL
What are the supportability and operability requirements?
Supportability is our ability to provide cost effective technical support. Our goal is to limit our support costs to only 5% of annual licensing fees. The product's automatic upgrade feature will help us easily deploy defect fixes to end-users. The user guide and product website will include a troubleshooting guide and checklist of information to have at hand before contacting technical support.
Operability is our ability to host and operate the software as an ASP (Application Service Provider). The product features should help us achieve our goal of 99.9% uptime (at most 43 minutes downtime each month). Key features supporting that are the ability to do hot data backups, and application monitoring.
Details:
DETAIL
DETAIL
DETAIL
What are the business life-cycle requirements?
The business life-cycle of a product includes everything that happens to that product over a period of several years, from initial purchase decision, through important but infrequent use cases, until product retirement. Key life-cycle requirements are listed below.
Details:
Customers must be able to manage the number of licenses that they have and make informed decisions to purchase more licenses when needed
The product shall support daily operations and our year-end audit
The customer data shall be stored in a format that is still accessible even after the application has been retired
Environmental Requirements
TODO: Describe the environmental requirements for this release. Environmental requirements describe the larger system of hardware, software, and data that this product must work within. Some examples are provided below.
What are the system hardware requirements?
PARAGRAPH
PARAGRAPH
Details:
DETAIL
DETAIL
DETAIL
What are the system software requirements?
PARAGRAPH
PARAGRAPH
Details:
DETAIL
DETAIL
DETAIL
What application program interfaces (APIs) must be provided?
PARAGRAPH
PARAGRAPH
Details:
We must implement this standard API.
DETAIL
DETAIL
What are the data import and export requirements?
PARAGRAPH
PARAGRAPH
Details:
The system will store all data in a standard SQL database, where it can be accessed by other programs.
The system will store all data in an XML file, using a standard DTD.
The system will read and write valid .XYZ files used by OTHER APPLICATION
DETAIL
TODO: Check for words of wisdom and discuss ways to improve this template. Or, evaluate the ReadySET Pro professional software requirements specification template.
Company Proprietary
Copyright © 2003-2004 Jason Robbins. All rights reserved. License terms. Retain this copyright statement whenever this file is used as a template.
Release Information
Project:
PROJECTNAME
Internal Release Number:
X.Y.Z
Attached worksheets:
SRS > Use case suite
SRS > Feature set
Related Documents:
Project proposal > User needs
LINKS TO RELEVANT STANDARDS
LINKS TO OTHER DOCUMENTS
Glossary
Process impact: The SRS precisely defines the software product that will be built. Decisions made in writing the SRS are based on information in the project proposal and user needs documents. The SRS sets requirements that must be satisfied by the system design. The SRS is verified and validated by activities outlined in the QA plan.
Introduction
TODO: Provide a brief overview of this release of the product. You can copy text from the project proposal, paste it here, and shorten it.
PARAGRAPH
PARAGRAPH
For more information, see the project proposal.
Use Cases
ONE PARAGRAPH OVERVIEW
Details:
Actors are described in the user needs document.
The use case suite lists all use cases in an organized way.
Functional Requirements
ONE PARAGRAPH OVERVIEW
Details:
The feature set lists all features in an organized way.
Non-Functional Requirements
TODO: Describe the non-functional requirements for this release. Some examples are provided below.
What are the usability requirements?
Our main criteria for making the system usable is the difficulty of performing each high-frequency use case. Difficulty depends on the number of steps, the knowledge that the user must have at each step, the decisions that the user must make at each step, and the mechanics of each step (e.g., typing a book title exactly is hard, clicking on a title in a list is easy).
The user interface should be as familiar as possible to users who have used other web applications and Windows desktop applications. E.g., we will follow the UI guidelines for naming menus, buttons, and dialog boxes whenever possible.
PARAGRAPH
Details:
Government customers will demand section508 compliance
Support learnability with principles of Instructive Interaction
The customer wants extensive on-line help, but is not demanding a printed manual.
What are the reliability and up-time requirements?
PARAGRAPH
PARAGRAPH
Details:
DETAIL
DETAIL
DETAIL
What are the safety requirements?
PARAGRAPH
PARAGRAPH
Details:
DETAIL
DETAIL
DETAIL
What are the security requirements?
Access will be controlled with usernames and passwords.
Only administrator users will have access to administrative functions, average users will not.
Details:
Passwords must be 4-14 characters long
We will not use encrypted communications (SSL) for this website
DETAIL
What are the performance and scalability requirements requirements?
PARAGRAPH
PARAGRAPH
Details:
DETAIL
DETAIL
DETAIL
What are the maintainability and upgradability requirements?
Maintainability is our ability to make changes to the product over time. We need strong maintainability in order to retain our early customers. We will address this by anticipating several types of change, and by carefully documenting our design and implementation.
Upgradability is our ability to cost-effectively deploy new versions of the product to customers with minimal downtime or disruption. A key feature supporting this goal is automatic download of patches and upgrade of the end-user's machine. Also, we shall use data file formats that include enough meta-data to allow us to reliably transform existing customer data during an upgrade.
Details:
DETAIL
DETAIL
DETAIL
What are the supportability and operability requirements?
Supportability is our ability to provide cost effective technical support. Our goal is to limit our support costs to only 5% of annual licensing fees. The product's automatic upgrade feature will help us easily deploy defect fixes to end-users. The user guide and product website will include a troubleshooting guide and checklist of information to have at hand before contacting technical support.
Operability is our ability to host and operate the software as an ASP (Application Service Provider). The product features should help us achieve our goal of 99.9% uptime (at most 43 minutes downtime each month). Key features supporting that are the ability to do hot data backups, and application monitoring.
Details:
DETAIL
DETAIL
DETAIL
What are the business life-cycle requirements?
The business life-cycle of a product includes everything that happens to that product over a period of several years, from initial purchase decision, through important but infrequent use cases, until product retirement. Key life-cycle requirements are listed below.
Details:
Customers must be able to manage the number of licenses that they have and make informed decisions to purchase more licenses when needed
The product shall support daily operations and our year-end audit
The customer data shall be stored in a format that is still accessible even after the application has been retired
Environmental Requirements
TODO: Describe the environmental requirements for this release. Environmental requirements describe the larger system of hardware, software, and data that this product must work within. Some examples are provided below.
What are the system hardware requirements?
PARAGRAPH
PARAGRAPH
Details:
DETAIL
DETAIL
DETAIL
What are the system software requirements?
PARAGRAPH
PARAGRAPH
Details:
DETAIL
DETAIL
DETAIL
What application program interfaces (APIs) must be provided?
PARAGRAPH
PARAGRAPH
Details:
We must implement this standard API.
DETAIL
DETAIL
What are the data import and export requirements?
PARAGRAPH
PARAGRAPH
Details:
The system will store all data in a standard SQL database, where it can be accessed by other programs.
The system will store all data in an XML file, using a standard DTD.
The system will read and write valid .XYZ files used by OTHER APPLICATION
DETAIL
TODO: Check for words of wisdom and discuss ways to improve this template. Or, evaluate the ReadySET Pro professional software requirements specification template.
Company Proprietary
Copyright © 2003-2004 Jason Robbins. All rights reserved. License terms. Retain this copyright statement whenever this file is used as a template.
C# e-book Containt
Programming C# for Beginners
Programming C# is a book written in step-by-step tutorial format for beginners and students who want to learn C# programming. It is recommended that you have some programming experience using any of the object-oriented languages such as C++, Pascal, or Java.
In this tutorial, you will learn how to write and compile C# programs; understand C# syntaxes, data types, control flow, classes and their members, interfaces, arrays, and exception handling. After completing this tutorial, you should have a clear understanding of the purpose of C# language, its usages, and how to write C# programs.
The current version of C# language is 3.0. This tutorial covers all versions of C# language including 1.0, 2.0, and 3.0. The features added in versions 2.0 and 3.0 are covered in the Advanced Topics of this tutorial.
Table of Contents
1.Introduction
2.C# Language Features
3.C# Editors & IDEs
4.C# Components
5.Types
6.Attributes
7.Variables
8.Constants
9.Expressions and Operators
10.Control Statements
11.Classes
12.Events
13.Indexers
14.Inheritance
15.C# 2.0 Features
16.C# 3.0 Features
1. Introduction
Microsoft developed C#, a new programming language based on the C and C++ languages. Microsoft describes C# in this way: ”C# is a simple, modern, object–oriented, and typesafe programming language derived from C and C++. C# (pronounced c sharp) is firmly planted in the C and C++ family tree of languages and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of visual basic and raw power of C++.”
Anders Hejlsberg, the principal architect of C#, is known for his work with Borland on Turbo Pascal and Delphi (based on object–oriented Pascal). After leaving Borland, Hejlsberg worked at Microsoft on Visual J++.
Some aspects of C# will be familiar to those, who have programmed in C, C++, or Java. C# incorporates the Smalltalk concept, which means everything is an object. In other words, all types in C# are objects. C# properties are similar to Visual Basic language properties. The Rapid Application Development (RAD) goal in C# is assisted by C#’s use of concepts and keyword, such as class, structure, statement, operator, and enumeration. The language also utilizes the concepts contained in the Component Object Model (COM) architecture.
Unlike Visual Basic or Delphi, Events is a type in C# and can belong to an object. Members of a class object can have variables, methods, properties, attributes, and events. Attributes are another nice feature of C# language.
NOTE: C# is a case sensitive language.
2. C# Language Features
C# was developed as a language that would combine the best features of previously existing Web and Windows programming languages. Many of the features in C# language are preexisted in various languages such as C++, Java, Pascal, and Visual Basic. Here is a list of some of the primary characteristics of C# language.
Modern and Object Oriented
Simple and Flexible
Typesafety
Automatic Memory Management
Versioning Control
Cross Platform Interoperability
Advanced features introduced in C# 2.0 and 3.0
a. Modern and Object Oriented
A modern language is one that provides latest features and tools for developing scalable, reliable, and robust industry–standard applications. C# is a modern language. The current trend in programming is Web development, and C# is the best language for developing web application and components for the Microsoft .NET platform.
As mentioned, C# is an object–oriented language. It supports all the basic object oriented language features: encapsulation, polymorphism, and inheritance.
b. Simple and Flexible
C# is as simple to use as Visual Basic, in that everything in C# represented as an object. All data type and components in C# are objects. C++ programmers are sometimes confused when choosing different access operators to process object. With C# you use a dot (.) operator to access the object members.
Programmers use C# to develop both managed and unmanaged code. Managed code is code managed through the CLR module. It handles garbage collection, type-safety, and platform-independence behavior. Unmanaged code, on the other hand is code run outside the CLR, such as an ActiveX control.
C# provides the flexibility of using native Win 32 application programming interface (API) and unmanaged code through COM+. C# enables you to declare unsafe classes and members having pointers, COM interfaces, structures, and native APIs. Although the class and its member are not typesafe, they still can be executed from managed code using COM+. Using the N/ Direct features of C# and COM+, you can use the C language API. With the help of the COM+ run-time and the COM+ Common Language Specification (CLS), you can access the COM and COM+ API. Using the Sysimport attribute, you can even access native Windows API (DLLs) in C#. See the “Attributes” section of this article for more about attributes.
c. Typesafety
C# is a typesafe language. All variables and classes (including primitive type, such as integer, Boolean, and float) in C# are a type, and all type are derived from the object the object type.
The object type provides basic functionality, such as string conversion, and information about a type. (See “The Object Class” section of this article for more about the object type.) C# doesn’t support unsafe type assignments. In other words, assigning a float variable directly to a Boolean variable is not permitted. If you assign a float type to a Boolean type, the compiler generates an error.
C# supports two kinds of type: value type and reference types. All value types are initialized with a value of zero, and all reference types are automatically initialized with a null value (local variable need to be initialized explicitly or the compiler throw a warning). The “Type in C#” section of this article will discuss types in more detail.
d. Automatic Memory Management and Garbage Collection
Automatic memory management and garbage collection are two important features of C#. With C#, you don’t need to allocate memory or release it. The garbage collection feature ensures that unused references are deleted and cleaned up in memory. You use the new operator to create type object, but you never need to call a delete operator to destroy the object. If the garbage collector finds any unreferenced object hanging around in memory, it removes it for you. Although you can’t call delete directly on an object, you have way to get garbage collector to destroy objects.
e. Versioning Control and Scalable
If you’re a Microsoft Window developer, you should be familiar with the expression DLL hell, which refers to having multiple versions of the same Dynamic Link Library (DLL) and not having backward and forward compatibility. For example, you can’t run programs written in Microsoft Foundation class (MFC) version4.0 on systems with MFC version 3.0 or earlier. This is one of the biggest challengers for a developer, especially if you’re developing MFC applications.
C# model is based on namespaces. All interfaces and classes must be bundled under a namespace. A namespace has classes as its members. You can access all the members or just a single member of a namespace. Two separate namespaces can have the same class as their member.
C# also supports binary compatibility with a base class. Adding a new method to a base class won’t cause any problems in your existing application.
The .NET assemblies contain metadata called manifest. A manifest stores information about an assembly such as its version, locale, and signature. There is no concept of registry entries for handing compatibility. In .NET, you simple put your assembly into one global folder if you want to make it sharable; otherwise, you put it in a private folder for private use only.
f. Language and Cross Platform Interoperability
C#, as with all Microsoft .NET supported language, shares a common .NET run-time library. The language compiler generates intermediate language (IL) code, which a .NET supported compiler can read with the help of the CLR. Therefore, you can use a C# assembly in VB.NET without any problem, and vice versa.
With the full support of COM+ and .NET framework services, C# has the ability to run on cross-platform systems. The Web-based applications created from .NET use an Extensible Markup Language (XML) model, which can run on multiple platforms.
g. Advanced Features introduced in C# 2.0 and 3.0
These features are discussed in more details in C# 2.0 Features and C# 3.0 Features sections of this tutorial.
The following features were introduced in C# version 2.0.
Partial classes
Generics
Nullable Types
Anonymous Methods
Iterators
Property Access Accessibility Modifiers
The following features were introduced in C# version 3.0.
Extension Methods
Implicit Typed Local Variables
Object and Collection Initializers
Query Expressions
Lambda Expressions
3. C# Editors and IDEs
Before starting your first C# application, you should take a look at the C# editors available for creating applications. Visual Studio .NET (VS.NET) Integrated Development Environment (IDE) is currently the best tool for developing C# applications. Installing VS .NET also installs the C# command-line compiler that comes with the .NET Software Development Kit (SDK).
If you don’t have VS.NET, you can install the C# command-line compiler by installing the .NET SDK. After installing the .NET SDK, you can use any C# editor.
Visual Studio 2005 Express is a lighter version of Visual Studio that is free to download. You can also download Visual C# 2005 Express version for free. To download these Express versions, go to MSDN website, select Downloads tab, and then select Visual Studio related link.
Tip: There are many C# editors available- some are even free. Many of the editors that use the C# command-line compiler are provided with the .NET SDK. Visit the C# Corner’s tools section (http://www.c-sharpcorner.com/tools.asp) for a list of available C# editor
If you can’t get one of these editors, you can use a text editor, such as Notepad or Word pad. In the next sections, you’ll learn how to write a windows forms application in notepad, and then you’ll look at the VS .NET IDE.
4. “Hello, C# Word!”
Let’s write our first simple “Hello, World!” program. The program will write output on your console saying, “Hello, C# word!”
Before starting with the C# programming, however you must install the C# compiler. The C# command-line compiler, csc.exe, comes with Microsoft’s .NET SDK. The .NET SDK supports the Windows 98, Windows ME, Windows NT 4.0 and Windows 2000 and later platforms.
After installing the compiler, type the code for the “HELLO, C# World!” program in any C# editor, which is shown in Listing 1. Then save the file as first.cs.
Listing 1. “Hello, C# world!” code
using System;
class Hello
{
static void Main()
{
Console.WriteLine("Hello, C# world!");
}
}
You can compile C# code from the command line using this syntax:
csc C:\\temp\first.cs
Make sure the path of your .cs file is correct and that the csc executable is included in your path. Also make sure that path of C# Compiler (csc.exe) is correct. After compiling your code, the C# compiler creates an .exe file called first.exe under the current directory. Now you can execute the .exe from window explorer or from the command line. Figure 1 shows the output.
Figure 1. “Hello, C# World!” program output
Did you see ”Hello, C# world!” on your console?
Yes? Congratulations!!! You’re now officially a C# programmer.
No? You may want to check the path of your file first.cs and the path of the compiler csc.exe.
You have now written your first few lines of C# code. But what does each line of your program means? I’ll describe the various components of your “Hello, C# world!” program.
The first line of your program is this:
using System;
The .NET framework class library is referenced in namespaces. The System namespace contains the Console class, which reads from or writes to the console.
The class keyword defines a new class that is followed by a class name, as seen in the second line of the “Hello, C# World!” code listing:
class Hello
{
...
}
The next line of code is the static void Main() function:
static void Main() {
Console.WriteLine ("Hello, C# World!");
}
}
In C#, every application must have a static Main() or int Main() entry point. The concept is similar to that of the Main() function of C++. This means, this is what a compiler will be looking for to start the application and whatever code is written in this method will be executed before any thing else.
The Console class is defined in the System namespace. You can access its class members by referencing them directly. Writeline(), A method of the Console class, writes a string and a line terminator to the console.
5. C# Components
Now that you’ve finished your first C# program, it’s time to talk about the intricacies of the C# language. In this section, I’ll discuss the C# syntax and components and how to use them.
Namespace and Assemblies
The first line of the “Hello, C# World!” program was this:
using System;
This line adds a reference to the System namespace to the program. After adding a reference to a namespace, you can access any member of the namespace. As mentioned, in .NET library references documentation, each class belongs to a namespace. But what exactly is a namespace?
To define .NET classes in a category so they’d be easy to recognize, Microsoft used the C++ class-packaging concept know as namespaces. A namespace is simply a grouping of related classes. The root of all namespaces is the System namespace. If you see namespaces in the .NET library, each class is defined in a group of similar category. For example, The System.Data namespace only possesses data-related classes, and System.Multithreading contains only multithreading classes.
When you create a new application using visual C#, you see that each application is defined as a namespace and that all classes belong to that namespace. You can access these classes from other application by referencing their namespaces.
For example, you can create a new namespace MyOtherNamespace with a method Hello defined in it. The Hello method writes “Hello, C# World!” to the console. Listing2 shows the namespace.
Listing 2 Namespace wrapper for the hello class
// Called namespace
namespace MyOtherNamespace
{
class MyOtherClass
{
public void Hello()
{
Console.WriteLine ("Hello, C# World!");
}
}
}
In listing 3, you’ll see how to reference this namespace and call MyOtherClass’s Hello method from the main program.
In listing 2, the MyOtherClass and its members can be accessed from other namespaces by either placing the statement using MyOtherNamespace before the class declaration or by referring to the class my other namespace before the class declaration or by referring to the class as MyOtherNamespace.Hello, as shown in listing 3 and listing 4.
Listing 3. Calling my other Namespace Name space members
using System;
using MyOtherNamespace;
// Caller namespace
namespace HelloWorldNamespace
{
class Hello
{
static void Main()
{
MyOtherClass cls = new MyOtherClass();
cls.Hello();
}
}
}
// Called namespace
namespace MyOtherNamespace
{
class MyOtherClass
{
public void Hello()
{
Console.WriteLine("Hello, C# World!");
}
}
}
As you have seen in listing 3, you include a namespace by adding the using directly. You can also reference a namespace direct without the using directive. Listing 4 shows you how to use MyOtherClass of MyOtherNamespace.
Listing 4. Calling the HelloWorld namespace member from the MyOtherNamespace
// Caller namespace
namespace HelloWorldNamespace
{
class Hello
{
static void Main()
{
MyOtherNamespace.MyOtherClass cls =
new MyOtherNamespace.MyOtherClass();
cls.Hello();
}
}
}
Standard Input and Output Streams
The System.Console class provides the capability to read streams from and write streams to the System console. It also defines functionality for error streams. The Read operation reads data from the console to the standard input stream, and the Write operation writes data to the standard output stream. The standard error stream is responsible for storing error data. These streams are the automatically associated with the system console.
The error, in, and out properties of the Console class represents standard error output, standard input and standard output streams. In the standard output stream, the Read method reads the next character, and the ReadLine method reads the next line. The Write and WriteLine methods write the data to the standard output stream. Table 1 describes some of the console class methods.
Table 1. The System.Console Class methods
METHOD
DESCRIPTION
EXAMPLE
Read
Reads a single character
int i = Console.Read();
ReadLline
Reads a line
string str = Console.ReadLine();
Write
Writes a line
Console.Write ("Write: 1");
WriteLine
Writes a line followed by a line terminator
Console.WriteLine("Test Output Data with Line");
Listing 5 shows you how to use the Console class and its members
Listing 5. Console class example
using System;
namespace ConsoleSamp
{
class Classs1
{
static void Main(string[ ] args )
{
Console.Write("Standard I/O Sample");
Console.WriteLine("");
Console.WriteLine ("= = = = = = = = ");
Console.WriteLine ("Enter your name . . .");
string name = Console.ReadLine();
Console.WriteLine("Output: Your name is : "+ name);
}
}
}
Figure2 shows the output of listing 5.
Figure 2. The console class methods output
The Object Class
As described, in the .NET framework, all types are represented as objects and are derived from the Object class. The Object class defines five methods: Equals, ReferenceEquals GetHashCode, GetType and ToString. Table 2 describes these methods, which are available to all types in the .NET library.
Table 2. Object class methods
METHOD
DESCRIPTION
GetType
Return type of the object.
Equals
Compares two object instances. Returns true if they’re Equal; otherwise false.
ReferenceEquals
Compares two object instances. Returns true if both are Same instance; otherwise false.
ToString
Converts an instance to a string type.
GetHashCode
Return hash code for an object.
The following sections discuss the object class methods in more detail.
The GetType method
You can use the Type class to retrieve type information from the object. The GetType method of an object return a type object, which you can use to get information on an object such as its name, namespace, base type, and so on. Listing 6 retrieves the information of objects. In Listing 6, you get the type of the Object and System.String classes.
Listing 6 GetType example
using System;
class TypeClass
{
static void Main(string [] args)
{
//create object of type object and string
Object cls1 = new Object ();
System.String cls2 = "Test string";
// Call Get Type to return the type
Type type1 = cls1.GetType( );
Type type2 =cls2.GetType( );
// Object class output
Console.WriteLine(type1.BaseType);
Console.WriteLine(type1.Name);
Console.WriteLine(type1.FullName);
Console.WriteLine(type1.Namespace);
// String output
Console.WriteLine(type2.BaseType);
Console.WriteLine(type2.Name);
Console.WriteLine(type2.FullName);
Console.WriteLine(type2.Namespace);
}
}
Figure 3 shows the output of listing 6.
Figure 3. Output of listing
The Equals and ReferenceEqual Methods
The Equals method in the Object class can compare two objects. The ReferenceEqual method can compare the two objects’ instances. For example:
Console.WriteLine(Object.Equals(cls1, cls2));
Console.WriteLine(Object.Equals(str1, str2));
See listing 7 get type, equal, and reference Equals
Listing 7. Get Type, Equal, and ReferenceEquals
using System;
namespace TypesSamp
{
//define class 1
public class Class1: object
{
private void Method1()
{
Console.WriteLine("1 method");
}
}
// Define class 2
public class Class2: Class1
{
private void Method2( )
{
Console.WriteLine("2 method");
}
}
class TypeClass
{
static void Main(string [] args)
{
Class1 cls1 = new Class1();
Class2 cls2 = new Class2();
Console.WriteLine ("= = = = = = = = = = ");
Console.WriteLine ("Type Information");
Console.WriteLine ("= = = = = = = = = =");
// Getting type information
Type type1 =cls1.GetType( );
Type type2 = cls2.GetType( );
Console.WriteLine(type1.BaseType);
Console.WriteLine(type1.Name);
Console.WriteLine(type1.FullName);
Console.WriteLine(type1.Namespace);
// Comparing two objects
string str1 = "Test";
string str2 = "Test";
Console.WriteLine(" = = = = = = = = = = = ");
Console.WriteLine("comparison of two objects");
Console.WriteLine(object.Equals(cls1, cls2));
Console.WriteLine(object.Equals(str1, str2));
}
}
}
Figure 4 shows the output of listing 7.
Figure 4 get type and compare objects code output
The ToString Method and String Conversion
The ToString method of the Object class converts a type to a string type.
Listing 8 shows an example of the ToString method.
Listing 8. ToString method example
using System;
namespace ToStringSamp
{
class Test
{
static void Main(string [] args)
{
int num1 =8;
float num2 =162.034f;
Console.WriteLine(num1.ToString( ));
Console.WriteLine(num2.ToString( ));
}
}
}
The GetHashCode method
A hashtable (also commonly known as a map or dictionary) is a data structure that stores one or more key- value pairs of data. Hashtables are useful when you want fast access to a list of data through a key (which can be a number, letter, string, or any object). In .NET the HashTable class represents a hashtable, which is implemented based on a hashing algorithm. This class also provides methods and constructors to define the size of the hash table. You can use the Add and Remove methods to add and remove items from a hashtable. The Count property of the HashTable class returns the number of items in a hashtable.
The GetHashCode method returns the hash code of an object. To return a hash code for a type, you must override the GetHashCode method. An integer value is returned, which represents whether an object is available in a hashtable.
Two other useful methods of the object class are MemberWiseClone and Finalize methods. The MemberWiseClone method creates a shallow copy of an object, which can be used as a clone of an object. The Finalize method acts as a destructor and can clean up the resources before the garbage collector calls the object. You need to override this method and write your own code to clean up the resources. The garbage collector automatically calls the Finalize method if an object is no longer in use.
6. Types
As mentioned earlier in the article, C# supports value types and reference types. Value types include simple data type such as int, char, and bool. Reference types include object, class, interface, and delegate.
A value type contains the actual value of the object. That means the actual data is stored in the variable of a value type, whereas a reference type variable contains the reference to the actual data.
Value Types
Value types reference the actual data and declared by using their default constructors. The default constructor of these types returns a zero- initialized instance of the variable. The value types can further be categorized instance of the variable. The value types can further be categorized into many subcategories, described in the following sections.
Simple Types
Simple types include basic data types such as int, char, and bool. These types have a reserved keyword corresponding to one class of a CLS type defined in the System class. For example, the keyword int aliases the System.Int32 type, and the keyword long aliases the System.Int64 type. Table 3 describes simple types.
Table 3 simple types
C# TYPE ALIAS
CLS TYPE
SIZE BITS
SUFFIX
DESCRIPTION
RANGE
sbyte
Sbyte
8
N/a
Singed byte
-128 to 127
byte
Byte
8
N/a
Unsigned byte
0 to 255
short
Int16
16
N/a
Short integer
-32,768 to 32,767
ushort
unit16
16
N/a
Unsigned short integer
0 to 65,535
int
Int32
32
N/a
Integer
-2,147,483,648 to 2,17483,648
uint
uint32
32
U
Unsigned integer
0 to 4,294,967,295
long
Int64
64
L
Long integer
-9223372036854775808 to 9223372036854775808
ulong
uint64
64
N/a
Unsigned long integer
0 to 18,446,744,073,709,551,615
char
char
16
N/a
Unicode character
any valid character, e.g., a,*, \x0058 (hex), or\u0058 (Unicode)
float
single
32
F
Floating point integer
double
double
64
D
Double floating point integer
bool
boolean
1
N/a
Logical true/false value
True/false
decimal
decimal
128
M
Used for financial and monetary calculations
One feature of simple types is that you can assign single direct values to these types. Listing 9 shows some assignment examples.
Listing 9. Simple type example
using System;
namespace ToStringSamp
{
class Test
{
static void Main(string[ ] args)
{
int num1 =12;
float num2 =3.05f;
double num3 = 3.5;
bool bl = true;
Console.WriteLine(num1.ToString());
Console.WriteLine(num2.ToString());
Console.WriteLine(num3.ToString());
Console.WriteLine(bl.ToString());
}
}
}
Struct Type
A struct type, or structure type, can declare constructors, constants, fields, methods, properties, indexers, operators, and nested types. Structure types are similar to classes, but they’re lightweight objects with no inheritance mechanism.
However, all structures inherit from the Object class.
In listing 10, your struct CarRec uses a record for a car with three members: name, model, and year.
Listing 10. a struct type example
using System;
struct CarRec
{
public string Name;
public string Model;
public int Year;
}
class TestStructureType
{
public static void Main ()
{
CarRec rec;
rec.Name ="Honda";
rec.Model ="Accord";
rec.Year = 1999;
Console.WriteLine("Car Name: " +rec.Name);
Console.WriteLine("Car Modal: " +rec.Model );
Console.WriteLine("Car: "+rec.Year);
}
}
Figure 5 shows the output of listing 10.
Figure 5. Output of listing 10
Enum data types
The enum data types are useful when you need to represent a set of multiple values. A good example of an enumeration is a list of colors:
enum ColorEnum {black, red, green};
Enum types are limited to long, int, short and byte.
This code declares an enum ColorEnum with members black, red, and green:
//black is 0, red is 1, green is 2.
enum ColorEnum{black, red, green};
You can also set your associated value to an e num type such as:
enum ColorEnum {black =0, red =1, green =2};
By default, enum associated value starts with 0 and increases by 1 for the next defined member. If you assign your value, the default value of the next e num type member will be the value of current member plus 1. For example, in this code the value of green is 7;
enum ColorEnum {black =0, red =6, green };
Reference Types
A reference type is a reference to an instance type. The main reference types are class, array, interface, delegate, and event. A null value is assigned to a reference type by default. A type assigned to a null value means the absence of an instance of that type.
Class Type
A class type defines a data structure that can have members in the form of methods, properties, indexers, events, constructors, operators, and delegates. The class keyword is used to create a class type. You can add methods, properties, indexers, delegates, and events to the class. Listing 11 shows an properties, indexers, delegates, and events to the class. Listing 11 shows an example of a class type.
Listing 11 Class Type example
// Define Class 1
public class class1:Object
{
private void Method1()
{
Console.WriteLine("1 method" );
}
}
The new keyword creates access to the class type. After creating an instance, you can use the dot (.) operator to access its members, as shows here:
Class1 cls1 = new class1();
cls1.Method1();
I’ll return to the discussion of classes later in this article.
Interface Type
An interface type is an abstract base class, which is a skeleton of a class and doesn’t implement the members that it defines. Only the derived class of an interface can implement the members of the interface. Interfaces can contain methods, properties, events, and indexers.
In listing 12 MyInterface is an interface that defines the method TestMethod.MyClass is derived from MyInterface, and you implement the MyMethod method in MyClass.
Listing 12. The interface type example
using System;
interface MyInterface
{
void TestMethod();
}
class MyClass:MyInterface
{
public static void Main()
{
MyClass cls=new MyClass();
cls.TestMethod();
}
public void TestMethod()
{
Console.WriteLine("Test Method");
}
}
A class can also implement multiple interfaces. Listing 13 defines two interfaces, MyInterface and MyInterface2.MyClass is inherited from these interfaces. You must implement these interfaces in the inherited class. If you don’t implement an interface in the derived class, the complier gives an error message.
For example, if you don’t implement the method test method TestMethod2 of MyInterface2 in Myclass, the compiler returns this message: “Myclass does not implement the interface member ‘MyInterface2. TestMethod2 (int, int)’.“
Listing 13. Multiple interfaces
using System;
interface MyInterface
{
void TestMethod();
}
interface MyInterface2
{
int TestMethod2(int a, int b);
}
class MyClass : MyInterface, MyInterface2
{
public static void main()
{
int num1 = 23;
int num2 = 6;
MyClass cls = new MyClass();
cls.TestMethod();
int tot = cls.TestMethod2(num1, num2);
Console.WriteLine(tot.ToString());
}
public void TestMethod()
{
Console.WriteLine("test method");
}
public int TestMethod2(int a, int b)
{
return a + b;
}
}
Delegates Types
Delegate types are mainly are used with the class events. A delegate type encapsulates a method with a certain signature, called a callable entity. Delegates are the typesafe and secure version of function pointers (callback functionality).
Delegate instances are not aware of the methods they encapsulate; they’re aware only and return type.
There are three steps in defining and using a delegate: declaration syntax. For example, this code:
delegate void MyDelegate():
Declares a delegate named MyDelegate that no arguments and returns void.
The next step is to create an instance of delegate and call it:
MyDelegate del =new MyDelegate(TestMethod);
del();
Listing 14 shows an example of delegate.
Listing 14. An example of delegate.
delegate void MyDelegate();
class Test
{
static void TestMethod()
{
System.Console.WriteLine("Test Method called");
}
static void Main()
{
MyDelegate del = new MyDelegate(TestMethod);
del();
}
}
Event Types
The event keyword defines an event. An eventype enables an object or class to provide notification of an event from the system. An instance of a delegate type encapsulates the callable entities. The EventHandler class defines a delegate definition. For example:
public delegate void EventHandler(object sender, System.Event Args e);
public event EventHandler Click;
...........
I’ll discuss events in more detail in the “Class Members” section of this article.
Array Types
An array type is a sequential set of any of the other types. Arrays can be either single- or multidimensional. Both rectangular and jagged arrays are supported a jagged array has elements that don’t necessarily have the same length. A rectangular array is multidimensional, and all of its subarrays have the same length. With arrays, all of the elements must be of the same base type. In C#, the lower index of an array starts with 0, and the upper index is number of item minus 1.
You can initialize array item either during the creation of an array or later by referencing array item, as shown here:
int[] nums = new int[5];
int[0] = 1;
int[1] = 2;
int[2] = 3;
int[3] = 4;
int[4] = 5;
Or here
int[] nums = new int {1,2,3,4,5,};
Listing 15 shows an example of single- dimensional arrays.
Listing 15. Single dimensional array example
class Test
{
static void Main()
{
//array of integers
int[] nums = new int[5];
// Array of strings
string[ ] names = new string[2];
for(int i =0; i< nums.Length; i++) nums[i] = i+2; names[0] = "Mahesh"; names[1] = "Chand"; for (int i = 0; i< nums.Length; i++) System.Console.WriteLine ("num[{0}] = {1}", i, nums[i] ); System.Console.WriteLine (names[0].ToString() + " " + names[1].ToString() ); } } The following is an example is an example of multiple, rectangular, and jagged arrays: char[] arr1 =new char[] {‘a‘, ‘b‘, ‘c’}; int[,] arrr2 = new int[,] {{2,4}, {3, 5}}; //rectangular array declaration int [, ,]arr3= new int[2,4,6]; // also rectangular int[][]jarr = new int[3][]; //jagged array declaration jarr[0] = new int[] {1,2,3}; jarr[1] = new int[] {1,2,3,4,5,6}; jarr[2] = new int[] {1,2,3,4,5,6,7,8,9}; Sorting Searching, and Copying Arrays The array class defines functionalities for creating, manipulating, searching, shorting, and copying arrays. Table4 lists and describes some of the array class properties. Table 4. The array class properties PROPERTY DESRIPITION Length Number of items in an array Rank Number of dimensions in an array IsFixedLength Indicates if an array is of fixed length IsReadOnly Indicates if an array is read-only Table 5 describes some of the array Class methods. Table 5. The array class methods METHOD DESCRIPTION BinarySearch Searches for an element using Binary search algorithm Clear Removes all elements of an array and set reference to null Copy Copies a section of one array to another CreateInstance Initializes a new instance of an array Reverse Reverses the order of array elements Sort Sorts the elements of an array Clone Creates a shallow copy of an array CopyTo Copies all elements from 1 D array to another GetLength Returns number of items in an array GetValue Gets a value at a specified location SetValue Sets a value at a specified location The Copy method copies one-array section to another array section. However, this method only works for single-dimensional array. Listing 16 shows a sample of coping array items from one array to another. Listing 16. Copying array sample using System; public class ArraySample { public static void Main() { // Create and initialize a new arrays int[] intArr = new int[5] {1,2,3,4,5}; Object[] objArr = new Object[5] {10,20,30,40,50}; foreach (int i in intArr) { Console.Write(i); Console.Write(","); } Console.WriteLine(); foreach (Object i in objArr ) { Console.Write (i); Console.Write (","); } Console.WriteLine(); // Copy one first 3 elements of intArr to objArr Array.Copy(intArr, objArr,3); Console.WriteLine("After coping" ); foreach (int i in intArr) { Console.Write(i); Console.Write(" , "); } Console.WriteLine( ); foreach (Object i in objArr) { Console.Write(i); Console.Write(" ,"); } Console.WriteLine( ); } } The Sort and Reverse methods of the array class are useful when you need to sort and reverse array elements. Listing 17 shows how to sort and reverse arrays. Listing 17. Reversing and sorting array elements using System; public class ArraySample { public static void Main() { // Create and initialize a new array instance. Array strArr = Array.CreateInstance(typeof(string), 3); strArr.SetValue("Mahesh", 0); strArr.SetValue("chand", 1); strArr.SetValue("Test Array", 2); // Display the values of the array. Console.WriteLine("Initial Array values:"); for (int i = strArr.GetLowerBound(0); i <= strArr.GetUpperBound(0); i++) Console.WriteLine(strArr.GetValue(i)); //sort the value of the array. Array.Sort(strArr); Console.WriteLine("After sorting:"); for (int i = strArr.GetLowerBound(0); i <= strArr.GetUpperBound(0); i++) Console.WriteLine(strArr.GetValue(i)); // Reverse values of the array. Array.Reverse(strArr); for (int i = strArr.GetLowerBound(0); i <= strArr.GetUpperBound(0); i++) Console.WriteLine(strArr.GetValue(i)); } } Type Conversions C# supports two kinds of type conversions: implicit conversions and explicit conversions. Some of the predefined types define predefined conversions, such as converting from an int type to a long type. Implicit conversions are conversions in which one type can directly and safely are converted to another type. Generally, small range type converts to large range type. As an example, you’ll examine the process of converting from an int type to a long type. In this conversion, there is no loss of data, as shown in Listing 18. Listing 18. Conversion example using System; class ConversionSamp { static void Main() { int num1 = 123; long num2 = num1; Console.WriteLine(num1.ToString()); Console.WriteLine(num2.ToString()); } } Casting performs explicit conversions. There may be a chance of data loss or even some errors in explicit conversions. For example, converting a long value to an integer would result in data loss. This is an example of an explicit conversion: long num1 = Int64.MaxValue; int num2 =(int)num1; Console.WriteLine(num1.ToString()); Console.WriteLine(num2.ToString()); The process of converting from a value type to a reference type is called boxing. Boxing is an implicit conversion. Listing 19 shows an example of boxing. Listing 19. Boxing example using System; class ConversionSamp { static void Main() { int num1 = 123; Object obj = num1; Console.WriteLine(num1.ToString()); Console.WriteLine(obj.ToString()); } } The process of converting from a reference type to a value type is called unboxing. Listing 20 shows an example of unboxing. Listing 20. Unboxing example using System; class ConversionSamp { static void Main() { Object obj = 123; int num1 = (int)obj; Console.WriteLine(num1.ToString()); Console.WriteLine(obj.ToString()); } } 7. Attributes Attributes enable the programmer to give certain declarative information to the elements in their class. These elements include the class itself, the methods, the fields, and the properties. You can choose to use some of the useful built-in attributes provided with the .NET platform, or you can create your own. Attributes are specified in square brackets ( [. . .] ) before the class element upon which they’re implemented. Table 6 shows some useful attributes provided with .NET. Table 6 Useful Built-in Attributes NAME DESCRIPTION EXAMPLE DllImport Imports a native DLL [DllImport(“winmm.dll”) ] Serializable Makes a class serializable [Serializable] Conditional Includes/omits a method based on condition [Conditional(Diagnostic”)] 8. Variables A variable represents a strong location. Each variable has a type that determines what values can be stored in the variable. A variable must definitely be assigned before its value can be obtained. In C#, you declare a variable in this format: [modifiers] datatype identifier; In this case, the modifier is an access modifier. The “variable Modifiers” section will discuss class member access modifiers. The data type refers to the type of value a variable can store. The identifier is the name of variable. The next two examples are declarations of variable where public is the modifier, int is the data type, and num1 is the name. The second variable type is a local variable. A local variable can’t have modifier because it sits inside a method and is always private to the method. Here are the examples: public int num1; and: int num1; A value can be assigned to variable after it’s declared. You can also initialize a value during a variable declaration. For example: int num1 = new Int16(); num1 = 34; int num2 = 123; Variable Modifiers Modifiers enable you to specify a number of features that you apply to your variable. You apply a variable modifier when you declare a variable. Keep in mind that mo-differs can be applied to fields not to local variables. Note: A local variable only has scope within its defined block in the program. A variable can have one or combination of more then one of the following types: internal, new, private, public, protected, read only, and static. Accessibility modifiers Some of the modifiers discussed in previous sections can set the accessibility level of variables. These are called accessibility modifiers (see table 7). Table 7. Accessibility modifiers MODIFIER DESCRIPTION internal The variable can only accessed by the current program. public The variable can be accessed from any where as a field. protected The variable can only be accessed with the class in which it’s defined and it’s derived class. protected internal The variable can only be accessed from the current program and the type derived from the current program. private The variable can only be accessed within the type in which it’s defined. You’ll now examine access modifiers in an example. In listing 21, AccessCls is a class accessed by the Main method. The Main method has access to num1 because it’s defined as a public variable, but not to num2 because it’s a private variable. Listing 21. Variable access modifiers. using System; class VarAccess { class AccessCls { public int num1 = 123; int num2 = 54; } static void Main() { AccessCls cls = new AccessCls(); int num1 = 98; num1 = cls.num1; //int i = cls. Num2; Console.WriteLine(num1.ToString()); } } When you access class members, the num2 variable is not available in the list of its members. See figure 6. Figure 6. Available members of AccessCls If you try access num2 from the main program, the compiler gives the error shown in figure 7 Figure 7. Error given when trying to access a private member of class Static and Read-Only Variables By default, a field is an instance field. That means a new copy of variable is creates for each instance of the class to which it belongs. There are some cases where you want the variable to be shared by ever instance of the class, and it’s in such cases that static fields are useful. By defining the static keyword, you can restrict a field to create only one instance of the variable of a class and share it with all other class instance of the same type. In other words, if you change the value of a static variable in a class, all instance at the class level rather then the instance level. You can use the static modifier alongside other modifiers. For example: public static int num2 = 34; You can modify the value of a variable once it’s initialized, but there are some cases where you don’t want to change the value of the variable after it’s assigned during initialization. In these cases, you can the read –only modifier to prevent modification. 9. Constants Constants are similar to read-only fields. You can’t change a constant value once it’s assigned. The const keyword precedes the field to define it as a constant. Assigning value to a constant would give a compilation error. For example: const int num3 = 34; num3 = 54; // Compilation error: the left-hand side of an assignment must // be a variable, property or indexer Although constant are similar to read-only fields, some differences exist. You can also declare local variables to be constants. Constants are always static, even though you don’t use the static keyword explicitly, so they’re shared by all instances of the class. 10. Expressions and Operators An expression is a sequence of operators and operands that specify some sort of computation. The operators indicate an operation to be applied to one or two operands. For example, the operators + and - indicate adding and subtracting operands. For example, the operator + and- indicate adding and subtracting one object from another, respectively. Listing 22 is a simple example of operators and operands. Listing 22. The relationship between operators and operands using System; class Test { static void Main() { int num1 = 123; int num2 = 34; int res = num1 + num2; Console.WriteLine(res.ToString()); res = -(res); Console. WriteLine(res.ToString()); } } This example applies an operator on two objects, num1 and num2: int res = num1 + num2; There are three types of operators: The unary operators take one operand and use either a prefix notation (Such as –x) or postfix notation (such as x++ ). The binary operators take two operands and all use what is called infix notation, where the operator appears between two objects (such as x + y). The ternary operator takes three operands and uses infix notation (such as c? x: y). Only one ternary operator, ?:, exists. Table 8 categorizes the operators. The table summarizes all operators in order of precedence from highest to lowest. Table 8. Operators in C# OPERATOR CAREGORY OPERATORS Primary x.y f(x) a[x] x++ x-- new typeof checked unchecked Unary + - ! ~ ++x --x (T)x Multiplicative * / % Additive + - Shift << >>
Relational and type testing
< > <= >= is as
Equality
== !=
Logical
AND &
Logical
XOR ^
Logical
OR |
Conditional
AND &&
Conditional
OR ||
Conditional
?:
Assignment
= *= /= %= += -= <<= >>= &= ^= |=
The checked and unchecked operators
The checked and unchecked operators are two new features in C# for C++ developers. These two operators force the CLR to handle stack overflow situations. The checked operators enforces overflow through an exception if an overflow occurs. The unchecked operator doesn’t throw an exception if an overflow occurs. Here the code throws an exception in the case of the checked operator, whereas the unchecked part of the same code won’t throw an exception:
checked
{
num1 += 5;
}
unchecked
{
num =+ 5;
}
The is operator
The is operator is useful when you need to check whether an object is compatible with a type. For example:
string str = "Mahesh";
if (str is object)
{
Console.WriteLine(str +" is an object compatible");
}
The sizeof Operator
The sizeof operator determines the size of a type. This operator can only be used in an unsafe context. By default, an unsafe context is false in VS.NET, so you’ll need to follow the right- click on the project > properties > Build option and set allow unsafe code blocks to use the unsafe block in your code. Then you’ll be able to compile the following code:
unsafe
{
Console.WriteLine(sizeof(int));
}
The typeof Operator
The typeof operator returns the type of a class or variable. It’s an alternative to GetType, discussed earlier in the “Objects in C#” section of this article.
For example:
Type t = typeof(MyClass);
The GetType operator returns a Type Object, which can access the type name and other type property information.
11. Control Statements
Control flow and program logic are of the most important parts of a programming language’s dynamic behavior. In this section, I’ll cover control flow in C#. Most of the condition and looping statements in C# comes from c and C++. Those who are familiar with java will recognize most of them, as well.
The if . . .else Statement
The if . . .else statement is inherited from C and C++. The if . . .else statement is also known as a conditional statement. For example:
if (condition)
statement
else
statement
The if. . .section of the statement or statement block is executed when the condition is true; if it’s false, control goes to the else statement or statement block. You can have a nested if . . .else statement with one of more else blocks.
You can also apply conditional or ( || ) and conditional and (&&) operators to combine more then one condition. Listing 23 shows you how to use the if. . .else statement.
Listing 23. The if . . . else statement example
using System;
public class MyClass
{
public static void Main()
{
int num1 = 6;
int num2 = 23;
int res = num1 + num2;
if (res > 25)
{
res = res - 5;
Console.WriteLine("Result is more then 25");
}
else
{
res = 25;
Console.WriteLine("Result is less then 25");
}
bool b = true;
if (res > 25 || b)
Console.WriteLine("Res > 25 or b is true");
else if ( (res>25) && !b )
Console.WriteLine("Res > 25 and b is false");
else
Console.WriteLine("else condition");
}
}
The switch Statement
Like the if . . . statement, the switch statement is also a conditional statement. It executes the case part if it matches with the switch value. If the switch value doesn’t match the case value, the default option executes .The switch statement is similar to an if . . . statement with multiple. . .else conditions, but it tends to be more readable. Note that in C#, you can now switch on string, which is something C++ did not previously allow. See listing 24 for an example of a switch statement.
Listing 24. The switch statement example
int i = 3;
switch(i)
{
case1:
Console.WriteLine("one");
break;
case2:
Console.WriteLine("two");
break;
case3:
Console.WriteLine("three");
break;
case4:
Console.WriteLine("four");
break;
case5:
Console.WriteLine("five");
break;
default:
Console.WriteLine("None of the about");
break;
}
The for loop Statement
The for loop statement is probably one of the widely used control statements for performing iterations in a loop. It executes a statement in the loop until the given guard condition is true. The for loop statement is a pretest loop, which means it first tests if a condition is true and only executes if it is. You can use the ++ or – operators to provide forward or backward looping. The following is an example of a for loop statement:
// Loop will execute 10 times from 0 to 9
for (int i=0; i<10; i++) { Console.WriteLine(i.ToString( ) ); } The while loop Statement The while loop statement also falls in the conditional loop category. The while loop statement executes unit the while condition is true. It’s also a pretest loop, which means it first tests if a condition is true and only continues execution if it is in the example shown here, the while loop statement executes until the value of i is less then 10; int i = 0; while (i<10) { Console.WriteLine(i.ToString()); i++; } The do . . . while loop Statement The do . . . while loop statement is a post- test loop, which means it executes a statement first and then checks if the condition is true. If the condition is true, the loop continues until the condition is false. As the name says, “do something while something is true.” This is an example of a do . . . while loop: int i = 0; do { Console.WriteLine(i.ToString()); i++; } while (i<10); The foreach loop statement The foreach loop statement is new concept to C++ programmers but will be familiar to veteran visual basic programmers. The foreach loop enables you to iterate over each element of an array or each element of a collection. This is a simple example: //foreach loop string[] strArr = {"Mahesh", "Chand", "Test String"}; foreach (string str in strArr) Console.WriteLine(str); In this example, the loop will continue until the items in the array are finished. Many of the collection examples in this article will use this loop. The go to statement The goto statement is used when you need to jump to a particular code segment. It’s similar to the goto statement in visual basic or C++. In the following code, if an item of array is found, the control goes to the level found and skips all code before that. Most programmers avoid using the goto statement, but you may find a rare need for it. One such occasion is the use of fall-through on a switch statement. Fall- thought is the ability for the control flow to fall from one case statement directly into another by leaving out the break statement. In C#, fall-though in a switch statement is not allowed as it was in C++. However, if you explicitly tell the switch statement to go to the next label, it will perform a jump to the next case, essentially carrying out the same function as a fall-through. Note that when using a go to in a case statement, you don’t have to provide a break (in all other cases, a break statement is mandatory). in this is bill” and “sometimes I’m called William” are displayed on the screen: Console.WriteLine("What is your name? "); string name = Console.ReadLine(); switch(name) { case "Bill": Console.WriteLine("My name is Bill."); goto case "William"; case "William": Console.WriteLine("Sometimes I’m called William."); break; case "Anne": Console.WriteLine("My name is Anne. "); break; default: break; } The break statement The break statement exits from a loop or a switch immediately. The break statement is usually applicable when you need to release control of the loop after a certain condition is met, or if you want to exit from the loop without executing the rest of the loop structure. You use it in for, foreach, while, and do. . . while loop statements. The following code shows the break statement. If condition j == 0 is true control will exit from the loop: for (int i=0; i<10; i++) { int j = i*i; Console.WriteLine(i.ToString()); if (j == 9) break; Console.WriteLine(j.ToString()); } The continue Statement Similar to the break statement, the continue statement also works in for, foreach, while, and do . . . while statements. The continue statement causes the loop to exit from the current iteration and continue with the rest of the iterations in the loop. See the following code for an example: for (int i=0; i<10; i++) { int j = i*i; Console.WriteLine("i is "+ i.ToString()); if (j == 9) Continue; Console.WriteLine("j is "+ j.ToString()); } In this code snippet, when the condition j == 9 is true, the control exits from the current iteration and moves to the next iteration. Note: The break statement makes control exits the entire loop, but the continue statement only skips the current iteration. The return Statement The return statement returns from a method before the end of that method is reached. The return statement can either a value or not, depending on the method that calls it. This is an example of a return statement that return nothing, and another where the return statement returns an integer value: public static void Main() { int output = 9 + 6; if ( output >= 12)
return;
Console.WriteLine ("Output less then 12");
}
public int Sum(int a, int b)
{
return a + b;
}
12. Classes
You saw a class structure in the “Hello, C# World!” sample. In the C#, you define a class by using the class keyword, just as you do in C++. Following the class keyword the class name and curly brackets ({. . .}), as shown here:
class Hello
{
static void Main()
{
Console.WriteLine("Hello, C# World!");
}
}
Note: C# classes don’t end semicolon (;) as C++.
Once a class is defined, you can add class members to it. Class members can include constants, fields, methods, properties, indexers, events, operators, instance constructors, static constructors, destructors, and nested type declarations. Each class member has an associated accessibility, which controls the scope of the member and defines whether these members are accessible outside the class.
Class Members
Table 9 describes allowable class member elements.
Table 9. A class members
CLASS MEMBER
INHERITANCE
Methods
Similar to C++ functions. Methods implement some action that can be performed by an object.
Properties
Provide access to a class attribute (a field). Useful for exposing fields in components.
Events
Used to provide notification.
Constants
Represents a constant value.
Fields
Represents a variable of the class
Operators
Used to define an expression (+, *,->, ++,[], and so on ).
Instance Constructors
Methods called during initialization of an object.
Static Constructors
Called automatically.
Destructors
Called when an object is being destroyed.
Indexers
A new concept in C#. An indexer provider indexing on an object. It allows you to treat a class as an array.
Types
All local types used in a class.
Before examining these members in detail, you’ll look at the accessibility of these members. Table 10 describes class member accessibility type and their scopes.
Table 10. Class member accessibility types and scopes
ACCESSIBLITY TYPE
SCOPE
Public
Member is accessible from other programs.
Protected
Member is accessible by the containing and its derived classes and types.
Internal
Member is accessible only the current program.
Protected internal
Member is accessible by the current program and the class derived from the containing class.
Now you’ll look at class members in more detail.
Fields
A field member Represent a variable of a class. In this example, strClassName is a string type public variable that can be accessed by the class instance:
class myClass
{
public static string strClassName;
public void SetClassName(string strName)
{
strClassName = strName;
}
}
As noted earlier; you can define field members as read-only. This means the field can only be assigned in the declaration or in the constructor of the class. See the following code:
class myClass
{
public static readonly string strClassName = "myClass";
public void SetClassName(string strName)
{
strClassName = strName; // illegal assignment
}
}
Note that the complier will throw an error because of an illegal assignment.
If the field is not static, you have to access fields from the class instance. It’s the same idea as accessing a public variable in the C++ or structure in C. for example:
myClass cls = new MyClass();
string clsName = cls.strClassName;
Constants
A constant Member represents a constant value throughout the program. For example the clsNodes is constant that has integer value 12. See the following code:
class myClass
{
public const int clsNodes = 12;
}
The value of clsNodes will be 12 throughout the program and can’t be reassigned.
Instance and Static Constructors
Constructors in C# are defined in the same way as in C++. C# supports two types of constructors: instance constructors and static constructors. Instance constructors are called every time a class is initialized. Static constructors are executed only once. Static constructors are for initialing the values of static variable. Listing 25 is an example of a class with a static constructor.
Listing 25. Calling Static Constructors
using System;
class myClass
{
static myClass()
{
Console.WriteLine("Initialieze clas ");
}
public static void foo()
{
Console.WriteLine(" foo");
}
}
class Test
{
static void Main()
{
myClass.foo();
//class myClass static constucter and then foo
}
}
Constructors can be overloaded, as shown in listing 26.
Listing 26. Over loaded Constructors example
class myClass
{
public int iCounter, iTotal;
public myClass()
{
iCounter = 0;
iTotal = 0;
}
public myClass (int iCount, int iTot)
{
iCounter = iCount;
iTotal = iTot;
}
}
Listing 27. Calling class constructors
using System;
class myClass
{
public int iCounter, iTotal;
public myClass()
{
iCounter = 0;
iTotal = 0;
}
public myClass(int iCount, int iTot )
{
iCounter = iCount;
iTotal = iTot;
}
}
class TestmyClass
{
static void Main()
{
myClass cls = new myClass();
myClass cls1 = new myClass(3, 4);
Console.WriteLine(cls1.iCounter.ToString());
Console.WriteLine(cls1.iTotal.ToString());
}
}
Destructors
A destructor is called when it’s time to destroy the object. Destructors can’t take parameters. See following code:
class myClass
{
~myClass()
{
// free resources
}
}
TIP: It’s not mandatory; in fact it’s unadvisable to call destructors. They’re called automatically by the CLR.
Methods
A method is a member that implements some functionality. It’s similar in appearance to the methods found in C++ and java. A method can return a value have, a list of parameters, and can be accessed through the class, whereas non - static. Static methods are accessed through the class, whereas non-static methods are accessed through the instance of the class. For example, listing 28 adds a method sum to the class myClass and called this method from the Main method.
Listing 28. Class method example
using System;
class myClass
{
public int Sum(int a, int b)
{
int res = a + b;
return res;
}
}
class TestmyClass
{
static void Main()
{
myClass cls = new myClass();
int total = cls.Sum(5, 8);
Console.WriteLine(total.ToString());
}
}
Methods in C# support function overloading in a similar way as C++. If you have programmed in C++, you’ll notice that C# methods are similar to C++ functions (and almost mirror those methods found in java). So it’s not a bad idea to call function overloading in C# method overloading. In listing 29, I over- overload the Sum method by passing in different types of values and call each of the overloaded Sum methods from the Main method.
Listing 29. Method overloading example
using System;
class myClass
{
public int Sum(int a, int b)
{
int res = a + b;
return res;
}
public float Sum(float a, float b)
{
float res = a + b;
return res;
}
public long Sum(long a, long b)
{
long res = a + b;
return res;
}
public long sum(long a, long b, long c)
{
long res = a + b + c;
return res;
}
public long Sum(int[] a)
{
int res = 0;
for (int i=0; i < a.Length; i++) { res += a[i]; } return res; } public void Sum() { //return nothing } } class TestmyClass { static void Main() { myClass cls = new myClass(); int intTot = cls.Sum(5,8); Console.WriteLine("Return integer sum:"+ intTot.ToString()); cls.Sum(); long longTot = cls.Sum(Int64.MaxValue - 30, 8); Console.WriteLine("Return long sum:" + longTot.ToString()); float floatTot = cls.Sum(Single.MaxValue-50, 8); Console.WriteLine("Return float sum:" + floatTot.ToString()); int[] myArray = new int[] {1,3,5,7,9}; Console.WriteLine("Return sum of array = {0}", cls.Sum(myArray).ToString()); } } The ref and out Parameters Did you ever need your method to return more than one value? You may need to do this occasionally, or you may need to use the same variables that you pass as an argument of the method. When you pass a reference type, such as a class instance, you don’t have to worry about getting a value in a separate variable because the type is already being passed as a reference and will maintain the changes when it returns. A problem occurs when you want the value to be returned in the value type. The ref and out parameters help to do this with value types. The out keyword defines an out type parameter. You Use the out keyword to pass a parameter to a method. This example is passing an integer type variable as an out parameter. You define a function with the out keyword as an argument with the variable type: myMethod(out int iVal1) The out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable. Listing 30 shows an example of the parameter. Listing 30. Using the out parameter using System; public class myClass { public static void ReturnData(out int iVal1, out int iVal2) { iVal1 = 2; iVal2 = 5; } public static void Main() { int iV1, iV2; // variable need not be initialized ReturnData(out iV1, out iV2); Console.WriteLine(iV1); Console.WriteLine(iV2); } } The ref keyword defines a ref type parameter. You pass a parameter to a method with this keyword, as in listing 31. This example passes an integer type variable as a ref parameter. This is a method definition: myMethod(ref int iVal1) You can use the ref parameter as a method input parameter and an output parameter. Any changes made to the parameter will be reflected in the variable. See listing 31 Listing 31. A ref parameter example using System; public class myClass { public static void ReturnData(ref int iVal1, ref int iVal2, ref int iVal3) { iVal1 +=2; iVal2 = iVal2*iVal2; iVal3 = iVal2 + iVal1; } public static void Main() { int iV1, iV2, iV3; // variable need not be initialized iV1 = 3; iV2 = 10; iV3 = 1; ReturnData(ref iV1, ref iV2, ref iV3); Console.WriteLine(iV1); Console.WriteLine(iV2); Console.WriteLine(iV3); } } In this method, ReturnData takes three values as input parameters, operates on the passed data returns the result in the same variable. Properties Other than methods, another important set of members of a class is variables. A variable is a type that stores some value. The property member of a class provides access to variables. Some examples of Properties are font type, color, and visible properties. Basically, Properties are fields. A field member can be accessed directly, but a property member is always accessed through accessor and modifier methods called get and set, respectively. If you have ever created active X controls in C++ or visual basic, or created JavaBeans in java, you understand. Note: Visual Basic programmers will note that Let is not available in C# This is because all types are objects, so only the set access or is necessary. In Listing 32 you create two properties of myClass:Age and MaleGender. Age is an integer property, and MaleGender is a Boolean type property. As you can see in the example, the get and set keywords are used to get and set property values. You’re reading and writing property values from the Main method. Note that leaving out the set method in a property makes the property read-only. Listing 32. Class property member example using System; class myClass { private bool bGender; private int intAge; // Gender property. public bool MaleGender { get { return bGender; } set { bGender = value; } } // Age property public int Age { get { return intAge; } set { intAge = value; } } } class TestmyClass { static void Main() { myClass cls = new myClass(); // set properties values cls.MaleGender = true; cls.Age = 25; if (cls.MaleGender) { Console.WriteLine("The Gender is Male"); Console.WriteLine("Age is" + cls. Age.ToString() ); } } } Why use properties if you already have the field available? First of all, properties expose fields in classes being used in components. They also provide a means for doing necessary computation before or after accessing or modifying the private fields they’re representing. For example, if you’re changing the color of a control in the set method, you may also want to execute an invalidate method inside the set to repaint the screen. 13. Events In C# events are a special type of delegate. An event member of a class provides notifications from user or machine input. A class defines an event by providing an event declaration, which is of type delegate. The following line shows the definition of an event handler: public delegate void EventHandler(object sender, System.EventArgs e); The EventHandler takes two arguments: one of type object and the other of type System.EvenArgs. A class implements the event handler using the event keyword. In the following example, MyControl class implements the EventHandler: public class MyControl { public event EvenHandler Click; public void Reset() { Click = null; } } You probably know that Windows is an event- driven operating system. In Windows programming, the system sends messages to the massage queue for every action taken by a user or the system, such as mouse–click, keyboard, touch screen, and timers. Even if the operating system is doing nothing, it still sends an idle message to the message queue after a certain interval of time. Although you usually use events in GUI applications, you can also implement events in console-based application. You can use them when you need to notify a state of an action. You’ll have a look at an example of both types. Listing 33 shows you how to implement events and event handlers in a console-based application. The Boiler.cs class defines the BoilerStatus event. The SetBoilerReading method sets the boiler temperature and pressure readings, and it writes the boiler status on the console based on the temperature and pressure reading. Boiler.cs defines BoilerStatus using the event keyword. Listing 33. Boiler.cs namespace BoilerEvent { using System; public class Boiler { public delegate void EngineHandler(int temp); public static event EngineHandler BoilerStatus; public Boiler() { } public void SetBoilerReading(int temp, int pressure) { if (BoilerStatus != null) { if (temp >=50 && pressure >= 60)
{
BoilerStatus(temp);
Console.WriteLine("Boiler Status: Temperature High");
}
else if (temp < 20 || pressure < 20) { BoilerStatus(temp); Console.WriteLine("Boiler status: Temperature Low"); } else Console.WriteLine("Boiler status: Temperature Normal"); } } } } Listing 34 is a caller class (main application) that calls the event through BoilerEventSink. The BoilerTempoMeter method of the sink generates a warning massage on the console only when the temperature of the boiler is zero. Listing 34. Caller of Boiler.Cs namespace BoilerEvent { using System; public class Boiler { // Boiler class here } public class BoilerEventSink { public void BoilerTempoMeter(int temp) { if (temp <= 0) { Console.WriteLine("Alarm: Boiler is switched off"); } } } // Event caller mailn application public class BoilerCallerApp { public static int Main(string [] args) { Boiler boiler1 = new Boiler(); BoilerEventSink bsink = new BoilerEventSink(); Boiler.BoilerStatus += new Boiler.EngineHandler( bsink.BoilerTempoMeter); boiler1.SetBoilerReadings (55, 74); boiler1.SetBoilerReadings (0, 54); boiler1.SetBoilerReadings (8, 23); return 0; } } } As you can see in Listing 34, I created a Boiler object that calls the BoilerStatus handler, which passes BoilerEventSink’s methods as an argument when calling Boiler. EngineHandler is a delegate defined in the Boiler class. Then the program calls the SetBoilerReading method with different temperature and pressure reading. When the temperature is zero, the program displays a warning message on the console; otherwise, the program displays message generated by the SetBoilerReading method. Actually, it’s easier to understand events using windows application than it is using a console-based application. To show you can an event sample in windows Forms, you’ll create a Windows application. In this application, you’ll create a form and a button. The button-click event executes and displays a message box. Here, the button-click event executes button1_click method: button1.Click += new System.EventHandler(button1_ Click); and the button-click handler looks like the following: private void button1_click(object sender, System.EventArgs e) { MassageBox.Show ("button is clicked"); } Listing 35 shows a windows forms program with event sample. If you compile this program, the out put looks like figure 8. Listing 35. Event Handling example using System; using System.Windows.Forms; using System.Drawing; namespace NotePadWindowsForms { public class NotePadWindowsForms: System.Windows.Forms.Form { private System.Windows.Forms.Button button1; public NotePadWindowsForms() { button1 = new System.Windows.Forms.Button(); // Button control and its properties button1.Location = new System.Drawing.Point(8, 32); button1.Name ="button1"; button1.Size = new System.Drawing.Size(104,32); button1.TabIndex = 0; button1.Text = "Click me"; // Adding controls to the form Controls.AddRange(new System.Windows.Forms.Control[] {button1} ); button1.Click += new System.EventHandler(button1_Click); } // Button click handler private void button1_Click(object sender, System.EventArgs e) { MessageBox.Show ("Button is clicked"); } public static int Main() { Application.Run(new NotePadWindowsForms()); return 0; } } } Figure 8 shows the output of listing 35 after clicking the Click me button. Figure 8 output of listing35 14. Indexers Indexers are a new concept in C#. Indexers enable a class object to function as an array. Implementing indexers is similar to implementing properties using the get and set functions. The only different is that when you call an indexer, you pass an indexing parameter. Accessing an indexer is similar to accessing an array. Indexers are nameless, so the this keyword declares indexers. I just said that after defining indexers, a class object could be treated as an array. What does that mean? To explain, I‘ll show you an example using the class called my class. The way you treat an instance of myClass now is like this: myClass cls = new myClass(); cls.MaleGender = true; After defining an indexer in myClass, you could treat an instance of it as if it were an array: myClass cls = new myClass(); cls[0].MaleGender = true; cls[1].MaleGender = true; You define indexer by using the this keyword as if were an array property of type object. Listing 36 shows the indexer signature of my class. Listing 36. Indexers of myClass public object this[int index] { get { if (! ValidIndex(index)) throw new Exception("Index out of range."); else return MaleGender(index).Value; } set { if (!ValidIndex(index) ) throw new Exception("Index out of range."); else MaleGender(index).Value = value; } } 15. Inheritance Inheritance is one of the main features of an object-oriented language. C# and the .NET class library are heavily based on inheritance. The telltale sign of this is that all .NET common library classes are derived from the object class, discussed at the beginning of this article. As pointed out, C# doesn’t support multiple Inheritance. C# only supports single inheritance; therefore, all objects are implicitly derived from the object class. Implementing inheritance in C# is similar to implementing it in C++. You use a colon (:) in the definition of a class to derive it from another class. In listing37, BaseClassB, which later accesses the BaseClassA method in the Main method. Listing 37. Inheritance example using System; // Base class A class BaseClassA { public void MethodA() { Console.WriteLine("A Method called"); } } // Base class B is derived from Base class A class BaseClassB:BaseClassA { public void MethodB() { Console.WriteLine("B method called"); } } class myClass { static void Main() { // Base class B BaseClassB b = new BaseClassB(); // Base class B method b.MethodB(); // BaseClassA Method through BaseClassB b.MethodA(); } } Note: The below sections will be updated in next version. 16. C# 2.0 Features Here is a list of new features added to C# version 2.0. 1.Partial Classes 2.Static Classes 3.Property Accessor Accessibility Modifier 4.Nullable Types 5.Generics 6.Anonymous Methods 7.Iterators 8.Friend Assemblies 1. Partial Classes Partial classes is one of the coolest feature added to C# language. Having partial classes in the language provides programmers to write cleaner interfaces. A partial class means "A single class can be defined in multiple physical files.". For example, I can have a ClassA, which is defined in three different AFile.cs, BFile.cs, and CFile.cs physical files. Now you may ask why would I want that? Do you remember ASP.NET or Windows Forms applications, where designer (Visual Studio IDE) generated code was written in a region and your code will be added after that. When writing larger user interface driven applications (for example Windows UI or Web UI), you may want to have user interfaces related code in a file, some logic in a separate file and so on. Now using partial classes, we can have designer generated code in a separate file, control event handlers in a separate file, and rest of the code in a separate file. 2. Static Classes C# 2.0 now supports static classes. Here are static classes properties. A static class cannot be instantiated. That means you cannot create an instance of a static class using new operator. A static class is a sealed class. That means you cannot inherit any class from a static class. A static class can have static members only. Having non-static member will generate a compiler error. A static class is less resource consuming and faster to compile and execute. Public static class MyStaticClass { Private static int myStaticVariable; Public static int StaticVariable; { Get { return myStaticVariable; } Set { myStaticVariable = value; } } Public static void Function() { } } 3. Property Accessor Accessibility Modifier C# 2.0 supports access modifiers for property accessor, which means now you can set access levels to get and set accessors of a property. For example, I can write a property something like this: public string LoginName { get { return loginName; } protected set { loginName = value; } } So now I can set LoginName property from any class derived from the class that has this property but I won't be able to set this property from other classes. This feature was not supported in previous version of C#. I create a class called ABaseClass, which has LoginName property: class ABaseClass { ///
/// Property Access Modifiers
///
private string loginName;
///
/// Login Name
///
public string LoginName
{
get { return loginName; }
protected set { loginName = value; }
}
}
Now I create a new class, which is derived from ABaseClass and in this class I set set LoginName property.
class ADerivedClass : ABaseClass
{
public void SetPrivateProperty()
{
base.LoginName = "mcb";
}
}
If I try to set the property value from other classes, I get the following error:
4. Nullable Types
One of the new features of C# 2.0 is nullable types. Now C# 2.0 allows you to assign null values to premitive types such as int, long, and bool.
The following code shows how to define an integer as nullable type and checks if the value of the integer is null or not.
///
/// Nullable types
///
public static void TestNullableTypes()
{
// Syntax to define nullable types
int? counter;
counter = 100;
if (counter != null)
{
// Assign null to an integer type
counter = null;
Console.WriteLine("Counter assigned null.");
}
else
{
Console.WriteLine("Counter cannot be assigned null.");
Console.ReadLine();
}
If you remove the "?" from int? counter, you will see a warning as following:
17. C# 3.0 Features
Updates will be in next version.
Summary
This article offered an overview of the new Microsoft language, C#. C# takes the best features of many present day programming languages. You became familiar with some of the language’s syntax. You learned how to write and compile your first command-line program with the “Hello, C# World!” example. You also became familiar with classes and their members, their scopes, and how to use them. You learned about some unique features, such as events the indexers, which were not available in languages such as C++. In the end of this article, you also saw the new advanced features added to version 2.0 and 3.0.
Programming C# is a book written in step-by-step tutorial format for beginners and students who want to learn C# programming. It is recommended that you have some programming experience using any of the object-oriented languages such as C++, Pascal, or Java.
In this tutorial, you will learn how to write and compile C# programs; understand C# syntaxes, data types, control flow, classes and their members, interfaces, arrays, and exception handling. After completing this tutorial, you should have a clear understanding of the purpose of C# language, its usages, and how to write C# programs.
The current version of C# language is 3.0. This tutorial covers all versions of C# language including 1.0, 2.0, and 3.0. The features added in versions 2.0 and 3.0 are covered in the Advanced Topics of this tutorial.
Table of Contents
1.Introduction
2.C# Language Features
3.C# Editors & IDEs
4.C# Components
5.Types
6.Attributes
7.Variables
8.Constants
9.Expressions and Operators
10.Control Statements
11.Classes
12.Events
13.Indexers
14.Inheritance
15.C# 2.0 Features
16.C# 3.0 Features
1. Introduction
Microsoft developed C#, a new programming language based on the C and C++ languages. Microsoft describes C# in this way: ”C# is a simple, modern, object–oriented, and typesafe programming language derived from C and C++. C# (pronounced c sharp) is firmly planted in the C and C++ family tree of languages and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of visual basic and raw power of C++.”
Anders Hejlsberg, the principal architect of C#, is known for his work with Borland on Turbo Pascal and Delphi (based on object–oriented Pascal). After leaving Borland, Hejlsberg worked at Microsoft on Visual J++.
Some aspects of C# will be familiar to those, who have programmed in C, C++, or Java. C# incorporates the Smalltalk concept, which means everything is an object. In other words, all types in C# are objects. C# properties are similar to Visual Basic language properties. The Rapid Application Development (RAD) goal in C# is assisted by C#’s use of concepts and keyword, such as class, structure, statement, operator, and enumeration. The language also utilizes the concepts contained in the Component Object Model (COM) architecture.
Unlike Visual Basic or Delphi, Events is a type in C# and can belong to an object. Members of a class object can have variables, methods, properties, attributes, and events. Attributes are another nice feature of C# language.
NOTE: C# is a case sensitive language.
2. C# Language Features
C# was developed as a language that would combine the best features of previously existing Web and Windows programming languages. Many of the features in C# language are preexisted in various languages such as C++, Java, Pascal, and Visual Basic. Here is a list of some of the primary characteristics of C# language.
Modern and Object Oriented
Simple and Flexible
Typesafety
Automatic Memory Management
Versioning Control
Cross Platform Interoperability
Advanced features introduced in C# 2.0 and 3.0
a. Modern and Object Oriented
A modern language is one that provides latest features and tools for developing scalable, reliable, and robust industry–standard applications. C# is a modern language. The current trend in programming is Web development, and C# is the best language for developing web application and components for the Microsoft .NET platform.
As mentioned, C# is an object–oriented language. It supports all the basic object oriented language features: encapsulation, polymorphism, and inheritance.
b. Simple and Flexible
C# is as simple to use as Visual Basic, in that everything in C# represented as an object. All data type and components in C# are objects. C++ programmers are sometimes confused when choosing different access operators to process object. With C# you use a dot (.) operator to access the object members.
Programmers use C# to develop both managed and unmanaged code. Managed code is code managed through the CLR module. It handles garbage collection, type-safety, and platform-independence behavior. Unmanaged code, on the other hand is code run outside the CLR, such as an ActiveX control.
C# provides the flexibility of using native Win 32 application programming interface (API) and unmanaged code through COM+. C# enables you to declare unsafe classes and members having pointers, COM interfaces, structures, and native APIs. Although the class and its member are not typesafe, they still can be executed from managed code using COM+. Using the N/ Direct features of C# and COM+, you can use the C language API. With the help of the COM+ run-time and the COM+ Common Language Specification (CLS), you can access the COM and COM+ API. Using the Sysimport attribute, you can even access native Windows API (DLLs) in C#. See the “Attributes” section of this article for more about attributes.
c. Typesafety
C# is a typesafe language. All variables and classes (including primitive type, such as integer, Boolean, and float) in C# are a type, and all type are derived from the object the object type.
The object type provides basic functionality, such as string conversion, and information about a type. (See “The Object Class” section of this article for more about the object type.) C# doesn’t support unsafe type assignments. In other words, assigning a float variable directly to a Boolean variable is not permitted. If you assign a float type to a Boolean type, the compiler generates an error.
C# supports two kinds of type: value type and reference types. All value types are initialized with a value of zero, and all reference types are automatically initialized with a null value (local variable need to be initialized explicitly or the compiler throw a warning). The “Type in C#” section of this article will discuss types in more detail.
d. Automatic Memory Management and Garbage Collection
Automatic memory management and garbage collection are two important features of C#. With C#, you don’t need to allocate memory or release it. The garbage collection feature ensures that unused references are deleted and cleaned up in memory. You use the new operator to create type object, but you never need to call a delete operator to destroy the object. If the garbage collector finds any unreferenced object hanging around in memory, it removes it for you. Although you can’t call delete directly on an object, you have way to get garbage collector to destroy objects.
e. Versioning Control and Scalable
If you’re a Microsoft Window developer, you should be familiar with the expression DLL hell, which refers to having multiple versions of the same Dynamic Link Library (DLL) and not having backward and forward compatibility. For example, you can’t run programs written in Microsoft Foundation class (MFC) version4.0 on systems with MFC version 3.0 or earlier. This is one of the biggest challengers for a developer, especially if you’re developing MFC applications.
C# model is based on namespaces. All interfaces and classes must be bundled under a namespace. A namespace has classes as its members. You can access all the members or just a single member of a namespace. Two separate namespaces can have the same class as their member.
C# also supports binary compatibility with a base class. Adding a new method to a base class won’t cause any problems in your existing application.
The .NET assemblies contain metadata called manifest. A manifest stores information about an assembly such as its version, locale, and signature. There is no concept of registry entries for handing compatibility. In .NET, you simple put your assembly into one global folder if you want to make it sharable; otherwise, you put it in a private folder for private use only.
f. Language and Cross Platform Interoperability
C#, as with all Microsoft .NET supported language, shares a common .NET run-time library. The language compiler generates intermediate language (IL) code, which a .NET supported compiler can read with the help of the CLR. Therefore, you can use a C# assembly in VB.NET without any problem, and vice versa.
With the full support of COM+ and .NET framework services, C# has the ability to run on cross-platform systems. The Web-based applications created from .NET use an Extensible Markup Language (XML) model, which can run on multiple platforms.
g. Advanced Features introduced in C# 2.0 and 3.0
These features are discussed in more details in C# 2.0 Features and C# 3.0 Features sections of this tutorial.
The following features were introduced in C# version 2.0.
Partial classes
Generics
Nullable Types
Anonymous Methods
Iterators
Property Access Accessibility Modifiers
The following features were introduced in C# version 3.0.
Extension Methods
Implicit Typed Local Variables
Object and Collection Initializers
Query Expressions
Lambda Expressions
3. C# Editors and IDEs
Before starting your first C# application, you should take a look at the C# editors available for creating applications. Visual Studio .NET (VS.NET) Integrated Development Environment (IDE) is currently the best tool for developing C# applications. Installing VS .NET also installs the C# command-line compiler that comes with the .NET Software Development Kit (SDK).
If you don’t have VS.NET, you can install the C# command-line compiler by installing the .NET SDK. After installing the .NET SDK, you can use any C# editor.
Visual Studio 2005 Express is a lighter version of Visual Studio that is free to download. You can also download Visual C# 2005 Express version for free. To download these Express versions, go to MSDN website, select Downloads tab, and then select Visual Studio related link.
Tip: There are many C# editors available- some are even free. Many of the editors that use the C# command-line compiler are provided with the .NET SDK. Visit the C# Corner’s tools section (http://www.c-sharpcorner.com/tools.asp) for a list of available C# editor
If you can’t get one of these editors, you can use a text editor, such as Notepad or Word pad. In the next sections, you’ll learn how to write a windows forms application in notepad, and then you’ll look at the VS .NET IDE.
4. “Hello, C# Word!”
Let’s write our first simple “Hello, World!” program. The program will write output on your console saying, “Hello, C# word!”
Before starting with the C# programming, however you must install the C# compiler. The C# command-line compiler, csc.exe, comes with Microsoft’s .NET SDK. The .NET SDK supports the Windows 98, Windows ME, Windows NT 4.0 and Windows 2000 and later platforms.
After installing the compiler, type the code for the “HELLO, C# World!” program in any C# editor, which is shown in Listing 1. Then save the file as first.cs.
Listing 1. “Hello, C# world!” code
using System;
class Hello
{
static void Main()
{
Console.WriteLine("Hello, C# world!");
}
}
You can compile C# code from the command line using this syntax:
csc C:\\temp\first.cs
Make sure the path of your .cs file is correct and that the csc executable is included in your path. Also make sure that path of C# Compiler (csc.exe) is correct. After compiling your code, the C# compiler creates an .exe file called first.exe under the current directory. Now you can execute the .exe from window explorer or from the command line. Figure 1 shows the output.
Figure 1. “Hello, C# World!” program output
Did you see ”Hello, C# world!” on your console?
Yes? Congratulations!!! You’re now officially a C# programmer.
No? You may want to check the path of your file first.cs and the path of the compiler csc.exe.
You have now written your first few lines of C# code. But what does each line of your program means? I’ll describe the various components of your “Hello, C# world!” program.
The first line of your program is this:
using System;
The .NET framework class library is referenced in namespaces. The System namespace contains the Console class, which reads from or writes to the console.
The class keyword defines a new class that is followed by a class name, as seen in the second line of the “Hello, C# World!” code listing:
class Hello
{
...
}
The next line of code is the static void Main() function:
static void Main() {
Console.WriteLine ("Hello, C# World!");
}
}
In C#, every application must have a static Main() or int Main() entry point. The concept is similar to that of the Main() function of C++. This means, this is what a compiler will be looking for to start the application and whatever code is written in this method will be executed before any thing else.
The Console class is defined in the System namespace. You can access its class members by referencing them directly. Writeline(), A method of the Console class, writes a string and a line terminator to the console.
5. C# Components
Now that you’ve finished your first C# program, it’s time to talk about the intricacies of the C# language. In this section, I’ll discuss the C# syntax and components and how to use them.
Namespace and Assemblies
The first line of the “Hello, C# World!” program was this:
using System;
This line adds a reference to the System namespace to the program. After adding a reference to a namespace, you can access any member of the namespace. As mentioned, in .NET library references documentation, each class belongs to a namespace. But what exactly is a namespace?
To define .NET classes in a category so they’d be easy to recognize, Microsoft used the C++ class-packaging concept know as namespaces. A namespace is simply a grouping of related classes. The root of all namespaces is the System namespace. If you see namespaces in the .NET library, each class is defined in a group of similar category. For example, The System.Data namespace only possesses data-related classes, and System.Multithreading contains only multithreading classes.
When you create a new application using visual C#, you see that each application is defined as a namespace and that all classes belong to that namespace. You can access these classes from other application by referencing their namespaces.
For example, you can create a new namespace MyOtherNamespace with a method Hello defined in it. The Hello method writes “Hello, C# World!” to the console. Listing2 shows the namespace.
Listing 2 Namespace wrapper for the hello class
// Called namespace
namespace MyOtherNamespace
{
class MyOtherClass
{
public void Hello()
{
Console.WriteLine ("Hello, C# World!");
}
}
}
In listing 3, you’ll see how to reference this namespace and call MyOtherClass’s Hello method from the main program.
In listing 2, the MyOtherClass and its members can be accessed from other namespaces by either placing the statement using MyOtherNamespace before the class declaration or by referring to the class my other namespace before the class declaration or by referring to the class as MyOtherNamespace.Hello, as shown in listing 3 and listing 4.
Listing 3. Calling my other Namespace Name space members
using System;
using MyOtherNamespace;
// Caller namespace
namespace HelloWorldNamespace
{
class Hello
{
static void Main()
{
MyOtherClass cls = new MyOtherClass();
cls.Hello();
}
}
}
// Called namespace
namespace MyOtherNamespace
{
class MyOtherClass
{
public void Hello()
{
Console.WriteLine("Hello, C# World!");
}
}
}
As you have seen in listing 3, you include a namespace by adding the using directly. You can also reference a namespace direct without the using directive. Listing 4 shows you how to use MyOtherClass of MyOtherNamespace.
Listing 4. Calling the HelloWorld namespace member from the MyOtherNamespace
// Caller namespace
namespace HelloWorldNamespace
{
class Hello
{
static void Main()
{
MyOtherNamespace.MyOtherClass cls =
new MyOtherNamespace.MyOtherClass();
cls.Hello();
}
}
}
Standard Input and Output Streams
The System.Console class provides the capability to read streams from and write streams to the System console. It also defines functionality for error streams. The Read operation reads data from the console to the standard input stream, and the Write operation writes data to the standard output stream. The standard error stream is responsible for storing error data. These streams are the automatically associated with the system console.
The error, in, and out properties of the Console class represents standard error output, standard input and standard output streams. In the standard output stream, the Read method reads the next character, and the ReadLine method reads the next line. The Write and WriteLine methods write the data to the standard output stream. Table 1 describes some of the console class methods.
Table 1. The System.Console Class methods
METHOD
DESCRIPTION
EXAMPLE
Read
Reads a single character
int i = Console.Read();
ReadLline
Reads a line
string str = Console.ReadLine();
Write
Writes a line
Console.Write ("Write: 1");
WriteLine
Writes a line followed by a line terminator
Console.WriteLine("Test Output Data with Line");
Listing 5 shows you how to use the Console class and its members
Listing 5. Console class example
using System;
namespace ConsoleSamp
{
class Classs1
{
static void Main(string[ ] args )
{
Console.Write("Standard I/O Sample");
Console.WriteLine("");
Console.WriteLine ("= = = = = = = = ");
Console.WriteLine ("Enter your name . . .");
string name = Console.ReadLine();
Console.WriteLine("Output: Your name is : "+ name);
}
}
}
Figure2 shows the output of listing 5.
Figure 2. The console class methods output
The Object Class
As described, in the .NET framework, all types are represented as objects and are derived from the Object class. The Object class defines five methods: Equals, ReferenceEquals GetHashCode, GetType and ToString. Table 2 describes these methods, which are available to all types in the .NET library.
Table 2. Object class methods
METHOD
DESCRIPTION
GetType
Return type of the object.
Equals
Compares two object instances. Returns true if they’re Equal; otherwise false.
ReferenceEquals
Compares two object instances. Returns true if both are Same instance; otherwise false.
ToString
Converts an instance to a string type.
GetHashCode
Return hash code for an object.
The following sections discuss the object class methods in more detail.
The GetType method
You can use the Type class to retrieve type information from the object. The GetType method of an object return a type object, which you can use to get information on an object such as its name, namespace, base type, and so on. Listing 6 retrieves the information of objects. In Listing 6, you get the type of the Object and System.String classes.
Listing 6 GetType example
using System;
class TypeClass
{
static void Main(string [] args)
{
//create object of type object and string
Object cls1 = new Object ();
System.String cls2 = "Test string";
// Call Get Type to return the type
Type type1 = cls1.GetType( );
Type type2 =cls2.GetType( );
// Object class output
Console.WriteLine(type1.BaseType);
Console.WriteLine(type1.Name);
Console.WriteLine(type1.FullName);
Console.WriteLine(type1.Namespace);
// String output
Console.WriteLine(type2.BaseType);
Console.WriteLine(type2.Name);
Console.WriteLine(type2.FullName);
Console.WriteLine(type2.Namespace);
}
}
Figure 3 shows the output of listing 6.
Figure 3. Output of listing
The Equals and ReferenceEqual Methods
The Equals method in the Object class can compare two objects. The ReferenceEqual method can compare the two objects’ instances. For example:
Console.WriteLine(Object.Equals(cls1, cls2));
Console.WriteLine(Object.Equals(str1, str2));
See listing 7 get type, equal, and reference Equals
Listing 7. Get Type, Equal, and ReferenceEquals
using System;
namespace TypesSamp
{
//define class 1
public class Class1: object
{
private void Method1()
{
Console.WriteLine("1 method");
}
}
// Define class 2
public class Class2: Class1
{
private void Method2( )
{
Console.WriteLine("2 method");
}
}
class TypeClass
{
static void Main(string [] args)
{
Class1 cls1 = new Class1();
Class2 cls2 = new Class2();
Console.WriteLine ("= = = = = = = = = = ");
Console.WriteLine ("Type Information");
Console.WriteLine ("= = = = = = = = = =");
// Getting type information
Type type1 =cls1.GetType( );
Type type2 = cls2.GetType( );
Console.WriteLine(type1.BaseType);
Console.WriteLine(type1.Name);
Console.WriteLine(type1.FullName);
Console.WriteLine(type1.Namespace);
// Comparing two objects
string str1 = "Test";
string str2 = "Test";
Console.WriteLine(" = = = = = = = = = = = ");
Console.WriteLine("comparison of two objects");
Console.WriteLine(object.Equals(cls1, cls2));
Console.WriteLine(object.Equals(str1, str2));
}
}
}
Figure 4 shows the output of listing 7.
Figure 4 get type and compare objects code output
The ToString Method and String Conversion
The ToString method of the Object class converts a type to a string type.
Listing 8 shows an example of the ToString method.
Listing 8. ToString method example
using System;
namespace ToStringSamp
{
class Test
{
static void Main(string [] args)
{
int num1 =8;
float num2 =162.034f;
Console.WriteLine(num1.ToString( ));
Console.WriteLine(num2.ToString( ));
}
}
}
The GetHashCode method
A hashtable (also commonly known as a map or dictionary) is a data structure that stores one or more key- value pairs of data. Hashtables are useful when you want fast access to a list of data through a key (which can be a number, letter, string, or any object). In .NET the HashTable class represents a hashtable, which is implemented based on a hashing algorithm. This class also provides methods and constructors to define the size of the hash table. You can use the Add and Remove methods to add and remove items from a hashtable. The Count property of the HashTable class returns the number of items in a hashtable.
The GetHashCode method returns the hash code of an object. To return a hash code for a type, you must override the GetHashCode method. An integer value is returned, which represents whether an object is available in a hashtable.
Two other useful methods of the object class are MemberWiseClone and Finalize methods. The MemberWiseClone method creates a shallow copy of an object, which can be used as a clone of an object. The Finalize method acts as a destructor and can clean up the resources before the garbage collector calls the object. You need to override this method and write your own code to clean up the resources. The garbage collector automatically calls the Finalize method if an object is no longer in use.
6. Types
As mentioned earlier in the article, C# supports value types and reference types. Value types include simple data type such as int, char, and bool. Reference types include object, class, interface, and delegate.
A value type contains the actual value of the object. That means the actual data is stored in the variable of a value type, whereas a reference type variable contains the reference to the actual data.
Value Types
Value types reference the actual data and declared by using their default constructors. The default constructor of these types returns a zero- initialized instance of the variable. The value types can further be categorized instance of the variable. The value types can further be categorized into many subcategories, described in the following sections.
Simple Types
Simple types include basic data types such as int, char, and bool. These types have a reserved keyword corresponding to one class of a CLS type defined in the System class. For example, the keyword int aliases the System.Int32 type, and the keyword long aliases the System.Int64 type. Table 3 describes simple types.
Table 3 simple types
C# TYPE ALIAS
CLS TYPE
SIZE BITS
SUFFIX
DESCRIPTION
RANGE
sbyte
Sbyte
8
N/a
Singed byte
-128 to 127
byte
Byte
8
N/a
Unsigned byte
0 to 255
short
Int16
16
N/a
Short integer
-32,768 to 32,767
ushort
unit16
16
N/a
Unsigned short integer
0 to 65,535
int
Int32
32
N/a
Integer
-2,147,483,648 to 2,17483,648
uint
uint32
32
U
Unsigned integer
0 to 4,294,967,295
long
Int64
64
L
Long integer
-9223372036854775808 to 9223372036854775808
ulong
uint64
64
N/a
Unsigned long integer
0 to 18,446,744,073,709,551,615
char
char
16
N/a
Unicode character
any valid character, e.g., a,*, \x0058 (hex), or\u0058 (Unicode)
float
single
32
F
Floating point integer
double
double
64
D
Double floating point integer
bool
boolean
1
N/a
Logical true/false value
True/false
decimal
decimal
128
M
Used for financial and monetary calculations
One feature of simple types is that you can assign single direct values to these types. Listing 9 shows some assignment examples.
Listing 9. Simple type example
using System;
namespace ToStringSamp
{
class Test
{
static void Main(string[ ] args)
{
int num1 =12;
float num2 =3.05f;
double num3 = 3.5;
bool bl = true;
Console.WriteLine(num1.ToString());
Console.WriteLine(num2.ToString());
Console.WriteLine(num3.ToString());
Console.WriteLine(bl.ToString());
}
}
}
Struct Type
A struct type, or structure type, can declare constructors, constants, fields, methods, properties, indexers, operators, and nested types. Structure types are similar to classes, but they’re lightweight objects with no inheritance mechanism.
However, all structures inherit from the Object class.
In listing 10, your struct CarRec uses a record for a car with three members: name, model, and year.
Listing 10. a struct type example
using System;
struct CarRec
{
public string Name;
public string Model;
public int Year;
}
class TestStructureType
{
public static void Main ()
{
CarRec rec;
rec.Name ="Honda";
rec.Model ="Accord";
rec.Year = 1999;
Console.WriteLine("Car Name: " +rec.Name);
Console.WriteLine("Car Modal: " +rec.Model );
Console.WriteLine("Car: "+rec.Year);
}
}
Figure 5 shows the output of listing 10.
Figure 5. Output of listing 10
Enum data types
The enum data types are useful when you need to represent a set of multiple values. A good example of an enumeration is a list of colors:
enum ColorEnum {black, red, green};
Enum types are limited to long, int, short and byte.
This code declares an enum ColorEnum with members black, red, and green:
//black is 0, red is 1, green is 2.
enum ColorEnum{black, red, green};
You can also set your associated value to an e num type such as:
enum ColorEnum {black =0, red =1, green =2};
By default, enum associated value starts with 0 and increases by 1 for the next defined member. If you assign your value, the default value of the next e num type member will be the value of current member plus 1. For example, in this code the value of green is 7;
enum ColorEnum {black =0, red =6, green };
Reference Types
A reference type is a reference to an instance type. The main reference types are class, array, interface, delegate, and event. A null value is assigned to a reference type by default. A type assigned to a null value means the absence of an instance of that type.
Class Type
A class type defines a data structure that can have members in the form of methods, properties, indexers, events, constructors, operators, and delegates. The class keyword is used to create a class type. You can add methods, properties, indexers, delegates, and events to the class. Listing 11 shows an properties, indexers, delegates, and events to the class. Listing 11 shows an example of a class type.
Listing 11 Class Type example
// Define Class 1
public class class1:Object
{
private void Method1()
{
Console.WriteLine("1 method" );
}
}
The new keyword creates access to the class type. After creating an instance, you can use the dot (.) operator to access its members, as shows here:
Class1 cls1 = new class1();
cls1.Method1();
I’ll return to the discussion of classes later in this article.
Interface Type
An interface type is an abstract base class, which is a skeleton of a class and doesn’t implement the members that it defines. Only the derived class of an interface can implement the members of the interface. Interfaces can contain methods, properties, events, and indexers.
In listing 12 MyInterface is an interface that defines the method TestMethod.MyClass is derived from MyInterface, and you implement the MyMethod method in MyClass.
Listing 12. The interface type example
using System;
interface MyInterface
{
void TestMethod();
}
class MyClass:MyInterface
{
public static void Main()
{
MyClass cls=new MyClass();
cls.TestMethod();
}
public void TestMethod()
{
Console.WriteLine("Test Method");
}
}
A class can also implement multiple interfaces. Listing 13 defines two interfaces, MyInterface and MyInterface2.MyClass is inherited from these interfaces. You must implement these interfaces in the inherited class. If you don’t implement an interface in the derived class, the complier gives an error message.
For example, if you don’t implement the method test method TestMethod2 of MyInterface2 in Myclass, the compiler returns this message: “Myclass does not implement the interface member ‘MyInterface2. TestMethod2 (int, int)’.“
Listing 13. Multiple interfaces
using System;
interface MyInterface
{
void TestMethod();
}
interface MyInterface2
{
int TestMethod2(int a, int b);
}
class MyClass : MyInterface, MyInterface2
{
public static void main()
{
int num1 = 23;
int num2 = 6;
MyClass cls = new MyClass();
cls.TestMethod();
int tot = cls.TestMethod2(num1, num2);
Console.WriteLine(tot.ToString());
}
public void TestMethod()
{
Console.WriteLine("test method");
}
public int TestMethod2(int a, int b)
{
return a + b;
}
}
Delegates Types
Delegate types are mainly are used with the class events. A delegate type encapsulates a method with a certain signature, called a callable entity. Delegates are the typesafe and secure version of function pointers (callback functionality).
Delegate instances are not aware of the methods they encapsulate; they’re aware only and return type.
There are three steps in defining and using a delegate: declaration syntax. For example, this code:
delegate void MyDelegate():
Declares a delegate named MyDelegate that no arguments and returns void.
The next step is to create an instance of delegate and call it:
MyDelegate del =new MyDelegate(TestMethod);
del();
Listing 14 shows an example of delegate.
Listing 14. An example of delegate.
delegate void MyDelegate();
class Test
{
static void TestMethod()
{
System.Console.WriteLine("Test Method called");
}
static void Main()
{
MyDelegate del = new MyDelegate(TestMethod);
del();
}
}
Event Types
The event keyword defines an event. An eventype enables an object or class to provide notification of an event from the system. An instance of a delegate type encapsulates the callable entities. The EventHandler class defines a delegate definition. For example:
public delegate void EventHandler(object sender, System.Event Args e);
public event EventHandler Click;
...........
I’ll discuss events in more detail in the “Class Members” section of this article.
Array Types
An array type is a sequential set of any of the other types. Arrays can be either single- or multidimensional. Both rectangular and jagged arrays are supported a jagged array has elements that don’t necessarily have the same length. A rectangular array is multidimensional, and all of its subarrays have the same length. With arrays, all of the elements must be of the same base type. In C#, the lower index of an array starts with 0, and the upper index is number of item minus 1.
You can initialize array item either during the creation of an array or later by referencing array item, as shown here:
int[] nums = new int[5];
int[0] = 1;
int[1] = 2;
int[2] = 3;
int[3] = 4;
int[4] = 5;
Or here
int[] nums = new int {1,2,3,4,5,};
Listing 15 shows an example of single- dimensional arrays.
Listing 15. Single dimensional array example
class Test
{
static void Main()
{
//array of integers
int[] nums = new int[5];
// Array of strings
string[ ] names = new string[2];
for(int i =0; i< nums.Length; i++) nums[i] = i+2; names[0] = "Mahesh"; names[1] = "Chand"; for (int i = 0; i< nums.Length; i++) System.Console.WriteLine ("num[{0}] = {1}", i, nums[i] ); System.Console.WriteLine (names[0].ToString() + " " + names[1].ToString() ); } } The following is an example is an example of multiple, rectangular, and jagged arrays: char[] arr1 =new char[] {‘a‘, ‘b‘, ‘c’}; int[,] arrr2 = new int[,] {{2,4}, {3, 5}}; //rectangular array declaration int [, ,]arr3= new int[2,4,6]; // also rectangular int[][]jarr = new int[3][]; //jagged array declaration jarr[0] = new int[] {1,2,3}; jarr[1] = new int[] {1,2,3,4,5,6}; jarr[2] = new int[] {1,2,3,4,5,6,7,8,9}; Sorting Searching, and Copying Arrays The array class defines functionalities for creating, manipulating, searching, shorting, and copying arrays. Table4 lists and describes some of the array class properties. Table 4. The array class properties PROPERTY DESRIPITION Length Number of items in an array Rank Number of dimensions in an array IsFixedLength Indicates if an array is of fixed length IsReadOnly Indicates if an array is read-only Table 5 describes some of the array Class methods. Table 5. The array class methods METHOD DESCRIPTION BinarySearch Searches for an element using Binary search algorithm Clear Removes all elements of an array and set reference to null Copy Copies a section of one array to another CreateInstance Initializes a new instance of an array Reverse Reverses the order of array elements Sort Sorts the elements of an array Clone Creates a shallow copy of an array CopyTo Copies all elements from 1 D array to another GetLength Returns number of items in an array GetValue Gets a value at a specified location SetValue Sets a value at a specified location The Copy method copies one-array section to another array section. However, this method only works for single-dimensional array. Listing 16 shows a sample of coping array items from one array to another. Listing 16. Copying array sample using System; public class ArraySample { public static void Main() { // Create and initialize a new arrays int[] intArr = new int[5] {1,2,3,4,5}; Object[] objArr = new Object[5] {10,20,30,40,50}; foreach (int i in intArr) { Console.Write(i); Console.Write(","); } Console.WriteLine(); foreach (Object i in objArr ) { Console.Write (i); Console.Write (","); } Console.WriteLine(); // Copy one first 3 elements of intArr to objArr Array.Copy(intArr, objArr,3); Console.WriteLine("After coping" ); foreach (int i in intArr) { Console.Write(i); Console.Write(" , "); } Console.WriteLine( ); foreach (Object i in objArr) { Console.Write(i); Console.Write(" ,"); } Console.WriteLine( ); } } The Sort and Reverse methods of the array class are useful when you need to sort and reverse array elements. Listing 17 shows how to sort and reverse arrays. Listing 17. Reversing and sorting array elements using System; public class ArraySample { public static void Main() { // Create and initialize a new array instance. Array strArr = Array.CreateInstance(typeof(string), 3); strArr.SetValue("Mahesh", 0); strArr.SetValue("chand", 1); strArr.SetValue("Test Array", 2); // Display the values of the array. Console.WriteLine("Initial Array values:"); for (int i = strArr.GetLowerBound(0); i <= strArr.GetUpperBound(0); i++) Console.WriteLine(strArr.GetValue(i)); //sort the value of the array. Array.Sort(strArr); Console.WriteLine("After sorting:"); for (int i = strArr.GetLowerBound(0); i <= strArr.GetUpperBound(0); i++) Console.WriteLine(strArr.GetValue(i)); // Reverse values of the array. Array.Reverse(strArr); for (int i = strArr.GetLowerBound(0); i <= strArr.GetUpperBound(0); i++) Console.WriteLine(strArr.GetValue(i)); } } Type Conversions C# supports two kinds of type conversions: implicit conversions and explicit conversions. Some of the predefined types define predefined conversions, such as converting from an int type to a long type. Implicit conversions are conversions in which one type can directly and safely are converted to another type. Generally, small range type converts to large range type. As an example, you’ll examine the process of converting from an int type to a long type. In this conversion, there is no loss of data, as shown in Listing 18. Listing 18. Conversion example using System; class ConversionSamp { static void Main() { int num1 = 123; long num2 = num1; Console.WriteLine(num1.ToString()); Console.WriteLine(num2.ToString()); } } Casting performs explicit conversions. There may be a chance of data loss or even some errors in explicit conversions. For example, converting a long value to an integer would result in data loss. This is an example of an explicit conversion: long num1 = Int64.MaxValue; int num2 =(int)num1; Console.WriteLine(num1.ToString()); Console.WriteLine(num2.ToString()); The process of converting from a value type to a reference type is called boxing. Boxing is an implicit conversion. Listing 19 shows an example of boxing. Listing 19. Boxing example using System; class ConversionSamp { static void Main() { int num1 = 123; Object obj = num1; Console.WriteLine(num1.ToString()); Console.WriteLine(obj.ToString()); } } The process of converting from a reference type to a value type is called unboxing. Listing 20 shows an example of unboxing. Listing 20. Unboxing example using System; class ConversionSamp { static void Main() { Object obj = 123; int num1 = (int)obj; Console.WriteLine(num1.ToString()); Console.WriteLine(obj.ToString()); } } 7. Attributes Attributes enable the programmer to give certain declarative information to the elements in their class. These elements include the class itself, the methods, the fields, and the properties. You can choose to use some of the useful built-in attributes provided with the .NET platform, or you can create your own. Attributes are specified in square brackets ( [. . .] ) before the class element upon which they’re implemented. Table 6 shows some useful attributes provided with .NET. Table 6 Useful Built-in Attributes NAME DESCRIPTION EXAMPLE DllImport Imports a native DLL [DllImport(“winmm.dll”) ] Serializable Makes a class serializable [Serializable] Conditional Includes/omits a method based on condition [Conditional(Diagnostic”)] 8. Variables A variable represents a strong location. Each variable has a type that determines what values can be stored in the variable. A variable must definitely be assigned before its value can be obtained. In C#, you declare a variable in this format: [modifiers] datatype identifier; In this case, the modifier is an access modifier. The “variable Modifiers” section will discuss class member access modifiers. The data type refers to the type of value a variable can store. The identifier is the name of variable. The next two examples are declarations of variable where public is the modifier, int is the data type, and num1 is the name. The second variable type is a local variable. A local variable can’t have modifier because it sits inside a method and is always private to the method. Here are the examples: public int num1; and: int num1; A value can be assigned to variable after it’s declared. You can also initialize a value during a variable declaration. For example: int num1 = new Int16(); num1 = 34; int num2 = 123; Variable Modifiers Modifiers enable you to specify a number of features that you apply to your variable. You apply a variable modifier when you declare a variable. Keep in mind that mo-differs can be applied to fields not to local variables. Note: A local variable only has scope within its defined block in the program. A variable can have one or combination of more then one of the following types: internal, new, private, public, protected, read only, and static. Accessibility modifiers Some of the modifiers discussed in previous sections can set the accessibility level of variables. These are called accessibility modifiers (see table 7). Table 7. Accessibility modifiers MODIFIER DESCRIPTION internal The variable can only accessed by the current program. public The variable can be accessed from any where as a field. protected The variable can only be accessed with the class in which it’s defined and it’s derived class. protected internal The variable can only be accessed from the current program and the type derived from the current program. private The variable can only be accessed within the type in which it’s defined. You’ll now examine access modifiers in an example. In listing 21, AccessCls is a class accessed by the Main method. The Main method has access to num1 because it’s defined as a public variable, but not to num2 because it’s a private variable. Listing 21. Variable access modifiers. using System; class VarAccess { class AccessCls { public int num1 = 123; int num2 = 54; } static void Main() { AccessCls cls = new AccessCls(); int num1 = 98; num1 = cls.num1; //int i = cls. Num2; Console.WriteLine(num1.ToString()); } } When you access class members, the num2 variable is not available in the list of its members. See figure 6. Figure 6. Available members of AccessCls If you try access num2 from the main program, the compiler gives the error shown in figure 7 Figure 7. Error given when trying to access a private member of class Static and Read-Only Variables By default, a field is an instance field. That means a new copy of variable is creates for each instance of the class to which it belongs. There are some cases where you want the variable to be shared by ever instance of the class, and it’s in such cases that static fields are useful. By defining the static keyword, you can restrict a field to create only one instance of the variable of a class and share it with all other class instance of the same type. In other words, if you change the value of a static variable in a class, all instance at the class level rather then the instance level. You can use the static modifier alongside other modifiers. For example: public static int num2 = 34; You can modify the value of a variable once it’s initialized, but there are some cases where you don’t want to change the value of the variable after it’s assigned during initialization. In these cases, you can the read –only modifier to prevent modification. 9. Constants Constants are similar to read-only fields. You can’t change a constant value once it’s assigned. The const keyword precedes the field to define it as a constant. Assigning value to a constant would give a compilation error. For example: const int num3 = 34; num3 = 54; // Compilation error: the left-hand side of an assignment must // be a variable, property or indexer Although constant are similar to read-only fields, some differences exist. You can also declare local variables to be constants. Constants are always static, even though you don’t use the static keyword explicitly, so they’re shared by all instances of the class. 10. Expressions and Operators An expression is a sequence of operators and operands that specify some sort of computation. The operators indicate an operation to be applied to one or two operands. For example, the operators + and - indicate adding and subtracting operands. For example, the operator + and- indicate adding and subtracting one object from another, respectively. Listing 22 is a simple example of operators and operands. Listing 22. The relationship between operators and operands using System; class Test { static void Main() { int num1 = 123; int num2 = 34; int res = num1 + num2; Console.WriteLine(res.ToString()); res = -(res); Console. WriteLine(res.ToString()); } } This example applies an operator on two objects, num1 and num2: int res = num1 + num2; There are three types of operators: The unary operators take one operand and use either a prefix notation (Such as –x) or postfix notation (such as x++ ). The binary operators take two operands and all use what is called infix notation, where the operator appears between two objects (such as x + y). The ternary operator takes three operands and uses infix notation (such as c? x: y). Only one ternary operator, ?:, exists. Table 8 categorizes the operators. The table summarizes all operators in order of precedence from highest to lowest. Table 8. Operators in C# OPERATOR CAREGORY OPERATORS Primary x.y f(x) a[x] x++ x-- new typeof checked unchecked Unary + - ! ~ ++x --x (T)x Multiplicative * / % Additive + - Shift << >>
Relational and type testing
< > <= >= is as
Equality
== !=
Logical
AND &
Logical
XOR ^
Logical
OR |
Conditional
AND &&
Conditional
OR ||
Conditional
?:
Assignment
= *= /= %= += -= <<= >>= &= ^= |=
The checked and unchecked operators
The checked and unchecked operators are two new features in C# for C++ developers. These two operators force the CLR to handle stack overflow situations. The checked operators enforces overflow through an exception if an overflow occurs. The unchecked operator doesn’t throw an exception if an overflow occurs. Here the code throws an exception in the case of the checked operator, whereas the unchecked part of the same code won’t throw an exception:
checked
{
num1 += 5;
}
unchecked
{
num =+ 5;
}
The is operator
The is operator is useful when you need to check whether an object is compatible with a type. For example:
string str = "Mahesh";
if (str is object)
{
Console.WriteLine(str +" is an object compatible");
}
The sizeof Operator
The sizeof operator determines the size of a type. This operator can only be used in an unsafe context. By default, an unsafe context is false in VS.NET, so you’ll need to follow the right- click on the project > properties > Build option and set allow unsafe code blocks to use the unsafe block in your code. Then you’ll be able to compile the following code:
unsafe
{
Console.WriteLine(sizeof(int));
}
The typeof Operator
The typeof operator returns the type of a class or variable. It’s an alternative to GetType, discussed earlier in the “Objects in C#” section of this article.
For example:
Type t = typeof(MyClass);
The GetType operator returns a Type Object, which can access the type name and other type property information.
11. Control Statements
Control flow and program logic are of the most important parts of a programming language’s dynamic behavior. In this section, I’ll cover control flow in C#. Most of the condition and looping statements in C# comes from c and C++. Those who are familiar with java will recognize most of them, as well.
The if . . .else Statement
The if . . .else statement is inherited from C and C++. The if . . .else statement is also known as a conditional statement. For example:
if (condition)
statement
else
statement
The if. . .section of the statement or statement block is executed when the condition is true; if it’s false, control goes to the else statement or statement block. You can have a nested if . . .else statement with one of more else blocks.
You can also apply conditional or ( || ) and conditional and (&&) operators to combine more then one condition. Listing 23 shows you how to use the if. . .else statement.
Listing 23. The if . . . else statement example
using System;
public class MyClass
{
public static void Main()
{
int num1 = 6;
int num2 = 23;
int res = num1 + num2;
if (res > 25)
{
res = res - 5;
Console.WriteLine("Result is more then 25");
}
else
{
res = 25;
Console.WriteLine("Result is less then 25");
}
bool b = true;
if (res > 25 || b)
Console.WriteLine("Res > 25 or b is true");
else if ( (res>25) && !b )
Console.WriteLine("Res > 25 and b is false");
else
Console.WriteLine("else condition");
}
}
The switch Statement
Like the if . . . statement, the switch statement is also a conditional statement. It executes the case part if it matches with the switch value. If the switch value doesn’t match the case value, the default option executes .The switch statement is similar to an if . . . statement with multiple. . .else conditions, but it tends to be more readable. Note that in C#, you can now switch on string, which is something C++ did not previously allow. See listing 24 for an example of a switch statement.
Listing 24. The switch statement example
int i = 3;
switch(i)
{
case1:
Console.WriteLine("one");
break;
case2:
Console.WriteLine("two");
break;
case3:
Console.WriteLine("three");
break;
case4:
Console.WriteLine("four");
break;
case5:
Console.WriteLine("five");
break;
default:
Console.WriteLine("None of the about");
break;
}
The for loop Statement
The for loop statement is probably one of the widely used control statements for performing iterations in a loop. It executes a statement in the loop until the given guard condition is true. The for loop statement is a pretest loop, which means it first tests if a condition is true and only executes if it is. You can use the ++ or – operators to provide forward or backward looping. The following is an example of a for loop statement:
// Loop will execute 10 times from 0 to 9
for (int i=0; i<10; i++) { Console.WriteLine(i.ToString( ) ); } The while loop Statement The while loop statement also falls in the conditional loop category. The while loop statement executes unit the while condition is true. It’s also a pretest loop, which means it first tests if a condition is true and only continues execution if it is in the example shown here, the while loop statement executes until the value of i is less then 10; int i = 0; while (i<10) { Console.WriteLine(i.ToString()); i++; } The do . . . while loop Statement The do . . . while loop statement is a post- test loop, which means it executes a statement first and then checks if the condition is true. If the condition is true, the loop continues until the condition is false. As the name says, “do something while something is true.” This is an example of a do . . . while loop: int i = 0; do { Console.WriteLine(i.ToString()); i++; } while (i<10); The foreach loop statement The foreach loop statement is new concept to C++ programmers but will be familiar to veteran visual basic programmers. The foreach loop enables you to iterate over each element of an array or each element of a collection. This is a simple example: //foreach loop string[] strArr = {"Mahesh", "Chand", "Test String"}; foreach (string str in strArr) Console.WriteLine(str); In this example, the loop will continue until the items in the array are finished. Many of the collection examples in this article will use this loop. The go to statement The goto statement is used when you need to jump to a particular code segment. It’s similar to the goto statement in visual basic or C++. In the following code, if an item of array is found, the control goes to the level found and skips all code before that. Most programmers avoid using the goto statement, but you may find a rare need for it. One such occasion is the use of fall-through on a switch statement. Fall- thought is the ability for the control flow to fall from one case statement directly into another by leaving out the break statement. In C#, fall-though in a switch statement is not allowed as it was in C++. However, if you explicitly tell the switch statement to go to the next label, it will perform a jump to the next case, essentially carrying out the same function as a fall-through. Note that when using a go to in a case statement, you don’t have to provide a break (in all other cases, a break statement is mandatory). in this is bill” and “sometimes I’m called William” are displayed on the screen: Console.WriteLine("What is your name? "); string name = Console.ReadLine(); switch(name) { case "Bill": Console.WriteLine("My name is Bill."); goto case "William"; case "William": Console.WriteLine("Sometimes I’m called William."); break; case "Anne": Console.WriteLine("My name is Anne. "); break; default: break; } The break statement The break statement exits from a loop or a switch immediately. The break statement is usually applicable when you need to release control of the loop after a certain condition is met, or if you want to exit from the loop without executing the rest of the loop structure. You use it in for, foreach, while, and do. . . while loop statements. The following code shows the break statement. If condition j == 0 is true control will exit from the loop: for (int i=0; i<10; i++) { int j = i*i; Console.WriteLine(i.ToString()); if (j == 9) break; Console.WriteLine(j.ToString()); } The continue Statement Similar to the break statement, the continue statement also works in for, foreach, while, and do . . . while statements. The continue statement causes the loop to exit from the current iteration and continue with the rest of the iterations in the loop. See the following code for an example: for (int i=0; i<10; i++) { int j = i*i; Console.WriteLine("i is "+ i.ToString()); if (j == 9) Continue; Console.WriteLine("j is "+ j.ToString()); } In this code snippet, when the condition j == 9 is true, the control exits from the current iteration and moves to the next iteration. Note: The break statement makes control exits the entire loop, but the continue statement only skips the current iteration. The return Statement The return statement returns from a method before the end of that method is reached. The return statement can either a value or not, depending on the method that calls it. This is an example of a return statement that return nothing, and another where the return statement returns an integer value: public static void Main() { int output = 9 + 6; if ( output >= 12)
return;
Console.WriteLine ("Output less then 12");
}
public int Sum(int a, int b)
{
return a + b;
}
12. Classes
You saw a class structure in the “Hello, C# World!” sample. In the C#, you define a class by using the class keyword, just as you do in C++. Following the class keyword the class name and curly brackets ({. . .}), as shown here:
class Hello
{
static void Main()
{
Console.WriteLine("Hello, C# World!");
}
}
Note: C# classes don’t end semicolon (;) as C++.
Once a class is defined, you can add class members to it. Class members can include constants, fields, methods, properties, indexers, events, operators, instance constructors, static constructors, destructors, and nested type declarations. Each class member has an associated accessibility, which controls the scope of the member and defines whether these members are accessible outside the class.
Class Members
Table 9 describes allowable class member elements.
Table 9. A class members
CLASS MEMBER
INHERITANCE
Methods
Similar to C++ functions. Methods implement some action that can be performed by an object.
Properties
Provide access to a class attribute (a field). Useful for exposing fields in components.
Events
Used to provide notification.
Constants
Represents a constant value.
Fields
Represents a variable of the class
Operators
Used to define an expression (+, *,->, ++,[], and so on ).
Instance Constructors
Methods called during initialization of an object.
Static Constructors
Called automatically.
Destructors
Called when an object is being destroyed.
Indexers
A new concept in C#. An indexer provider indexing on an object. It allows you to treat a class as an array.
Types
All local types used in a class.
Before examining these members in detail, you’ll look at the accessibility of these members. Table 10 describes class member accessibility type and their scopes.
Table 10. Class member accessibility types and scopes
ACCESSIBLITY TYPE
SCOPE
Public
Member is accessible from other programs.
Protected
Member is accessible by the containing and its derived classes and types.
Internal
Member is accessible only the current program.
Protected internal
Member is accessible by the current program and the class derived from the containing class.
Now you’ll look at class members in more detail.
Fields
A field member Represent a variable of a class. In this example, strClassName is a string type public variable that can be accessed by the class instance:
class myClass
{
public static string strClassName;
public void SetClassName(string strName)
{
strClassName = strName;
}
}
As noted earlier; you can define field members as read-only. This means the field can only be assigned in the declaration or in the constructor of the class. See the following code:
class myClass
{
public static readonly string strClassName = "myClass";
public void SetClassName(string strName)
{
strClassName = strName; // illegal assignment
}
}
Note that the complier will throw an error because of an illegal assignment.
If the field is not static, you have to access fields from the class instance. It’s the same idea as accessing a public variable in the C++ or structure in C. for example:
myClass cls = new MyClass();
string clsName = cls.strClassName;
Constants
A constant Member represents a constant value throughout the program. For example the clsNodes is constant that has integer value 12. See the following code:
class myClass
{
public const int clsNodes = 12;
}
The value of clsNodes will be 12 throughout the program and can’t be reassigned.
Instance and Static Constructors
Constructors in C# are defined in the same way as in C++. C# supports two types of constructors: instance constructors and static constructors. Instance constructors are called every time a class is initialized. Static constructors are executed only once. Static constructors are for initialing the values of static variable. Listing 25 is an example of a class with a static constructor.
Listing 25. Calling Static Constructors
using System;
class myClass
{
static myClass()
{
Console.WriteLine("Initialieze clas ");
}
public static void foo()
{
Console.WriteLine(" foo");
}
}
class Test
{
static void Main()
{
myClass.foo();
//class myClass static constucter and then foo
}
}
Constructors can be overloaded, as shown in listing 26.
Listing 26. Over loaded Constructors example
class myClass
{
public int iCounter, iTotal;
public myClass()
{
iCounter = 0;
iTotal = 0;
}
public myClass (int iCount, int iTot)
{
iCounter = iCount;
iTotal = iTot;
}
}
Listing 27. Calling class constructors
using System;
class myClass
{
public int iCounter, iTotal;
public myClass()
{
iCounter = 0;
iTotal = 0;
}
public myClass(int iCount, int iTot )
{
iCounter = iCount;
iTotal = iTot;
}
}
class TestmyClass
{
static void Main()
{
myClass cls = new myClass();
myClass cls1 = new myClass(3, 4);
Console.WriteLine(cls1.iCounter.ToString());
Console.WriteLine(cls1.iTotal.ToString());
}
}
Destructors
A destructor is called when it’s time to destroy the object. Destructors can’t take parameters. See following code:
class myClass
{
~myClass()
{
// free resources
}
}
TIP: It’s not mandatory; in fact it’s unadvisable to call destructors. They’re called automatically by the CLR.
Methods
A method is a member that implements some functionality. It’s similar in appearance to the methods found in C++ and java. A method can return a value have, a list of parameters, and can be accessed through the class, whereas non - static. Static methods are accessed through the class, whereas non-static methods are accessed through the instance of the class. For example, listing 28 adds a method sum to the class myClass and called this method from the Main method.
Listing 28. Class method example
using System;
class myClass
{
public int Sum(int a, int b)
{
int res = a + b;
return res;
}
}
class TestmyClass
{
static void Main()
{
myClass cls = new myClass();
int total = cls.Sum(5, 8);
Console.WriteLine(total.ToString());
}
}
Methods in C# support function overloading in a similar way as C++. If you have programmed in C++, you’ll notice that C# methods are similar to C++ functions (and almost mirror those methods found in java). So it’s not a bad idea to call function overloading in C# method overloading. In listing 29, I over- overload the Sum method by passing in different types of values and call each of the overloaded Sum methods from the Main method.
Listing 29. Method overloading example
using System;
class myClass
{
public int Sum(int a, int b)
{
int res = a + b;
return res;
}
public float Sum(float a, float b)
{
float res = a + b;
return res;
}
public long Sum(long a, long b)
{
long res = a + b;
return res;
}
public long sum(long a, long b, long c)
{
long res = a + b + c;
return res;
}
public long Sum(int[] a)
{
int res = 0;
for (int i=0; i < a.Length; i++) { res += a[i]; } return res; } public void Sum() { //return nothing } } class TestmyClass { static void Main() { myClass cls = new myClass(); int intTot = cls.Sum(5,8); Console.WriteLine("Return integer sum:"+ intTot.ToString()); cls.Sum(); long longTot = cls.Sum(Int64.MaxValue - 30, 8); Console.WriteLine("Return long sum:" + longTot.ToString()); float floatTot = cls.Sum(Single.MaxValue-50, 8); Console.WriteLine("Return float sum:" + floatTot.ToString()); int[] myArray = new int[] {1,3,5,7,9}; Console.WriteLine("Return sum of array = {0}", cls.Sum(myArray).ToString()); } } The ref and out Parameters Did you ever need your method to return more than one value? You may need to do this occasionally, or you may need to use the same variables that you pass as an argument of the method. When you pass a reference type, such as a class instance, you don’t have to worry about getting a value in a separate variable because the type is already being passed as a reference and will maintain the changes when it returns. A problem occurs when you want the value to be returned in the value type. The ref and out parameters help to do this with value types. The out keyword defines an out type parameter. You Use the out keyword to pass a parameter to a method. This example is passing an integer type variable as an out parameter. You define a function with the out keyword as an argument with the variable type: myMethod(out int iVal1) The out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable. Listing 30 shows an example of the parameter. Listing 30. Using the out parameter using System; public class myClass { public static void ReturnData(out int iVal1, out int iVal2) { iVal1 = 2; iVal2 = 5; } public static void Main() { int iV1, iV2; // variable need not be initialized ReturnData(out iV1, out iV2); Console.WriteLine(iV1); Console.WriteLine(iV2); } } The ref keyword defines a ref type parameter. You pass a parameter to a method with this keyword, as in listing 31. This example passes an integer type variable as a ref parameter. This is a method definition: myMethod(ref int iVal1) You can use the ref parameter as a method input parameter and an output parameter. Any changes made to the parameter will be reflected in the variable. See listing 31 Listing 31. A ref parameter example using System; public class myClass { public static void ReturnData(ref int iVal1, ref int iVal2, ref int iVal3) { iVal1 +=2; iVal2 = iVal2*iVal2; iVal3 = iVal2 + iVal1; } public static void Main() { int iV1, iV2, iV3; // variable need not be initialized iV1 = 3; iV2 = 10; iV3 = 1; ReturnData(ref iV1, ref iV2, ref iV3); Console.WriteLine(iV1); Console.WriteLine(iV2); Console.WriteLine(iV3); } } In this method, ReturnData takes three values as input parameters, operates on the passed data returns the result in the same variable. Properties Other than methods, another important set of members of a class is variables. A variable is a type that stores some value. The property member of a class provides access to variables. Some examples of Properties are font type, color, and visible properties. Basically, Properties are fields. A field member can be accessed directly, but a property member is always accessed through accessor and modifier methods called get and set, respectively. If you have ever created active X controls in C++ or visual basic, or created JavaBeans in java, you understand. Note: Visual Basic programmers will note that Let is not available in C# This is because all types are objects, so only the set access or is necessary. In Listing 32 you create two properties of myClass:Age and MaleGender. Age is an integer property, and MaleGender is a Boolean type property. As you can see in the example, the get and set keywords are used to get and set property values. You’re reading and writing property values from the Main method. Note that leaving out the set method in a property makes the property read-only. Listing 32. Class property member example using System; class myClass { private bool bGender; private int intAge; // Gender property. public bool MaleGender { get { return bGender; } set { bGender = value; } } // Age property public int Age { get { return intAge; } set { intAge = value; } } } class TestmyClass { static void Main() { myClass cls = new myClass(); // set properties values cls.MaleGender = true; cls.Age = 25; if (cls.MaleGender) { Console.WriteLine("The Gender is Male"); Console.WriteLine("Age is" + cls. Age.ToString() ); } } } Why use properties if you already have the field available? First of all, properties expose fields in classes being used in components. They also provide a means for doing necessary computation before or after accessing or modifying the private fields they’re representing. For example, if you’re changing the color of a control in the set method, you may also want to execute an invalidate method inside the set to repaint the screen. 13. Events In C# events are a special type of delegate. An event member of a class provides notifications from user or machine input. A class defines an event by providing an event declaration, which is of type delegate. The following line shows the definition of an event handler: public delegate void EventHandler(object sender, System.EventArgs e); The EventHandler takes two arguments: one of type object and the other of type System.EvenArgs. A class implements the event handler using the event keyword. In the following example, MyControl class implements the EventHandler: public class MyControl { public event EvenHandler Click; public void Reset() { Click = null; } } You probably know that Windows is an event- driven operating system. In Windows programming, the system sends messages to the massage queue for every action taken by a user or the system, such as mouse–click, keyboard, touch screen, and timers. Even if the operating system is doing nothing, it still sends an idle message to the message queue after a certain interval of time. Although you usually use events in GUI applications, you can also implement events in console-based application. You can use them when you need to notify a state of an action. You’ll have a look at an example of both types. Listing 33 shows you how to implement events and event handlers in a console-based application. The Boiler.cs class defines the BoilerStatus event. The SetBoilerReading method sets the boiler temperature and pressure readings, and it writes the boiler status on the console based on the temperature and pressure reading. Boiler.cs defines BoilerStatus using the event keyword. Listing 33. Boiler.cs namespace BoilerEvent { using System; public class Boiler { public delegate void EngineHandler(int temp); public static event EngineHandler BoilerStatus; public Boiler() { } public void SetBoilerReading(int temp, int pressure) { if (BoilerStatus != null) { if (temp >=50 && pressure >= 60)
{
BoilerStatus(temp);
Console.WriteLine("Boiler Status: Temperature High");
}
else if (temp < 20 || pressure < 20) { BoilerStatus(temp); Console.WriteLine("Boiler status: Temperature Low"); } else Console.WriteLine("Boiler status: Temperature Normal"); } } } } Listing 34 is a caller class (main application) that calls the event through BoilerEventSink. The BoilerTempoMeter method of the sink generates a warning massage on the console only when the temperature of the boiler is zero. Listing 34. Caller of Boiler.Cs namespace BoilerEvent { using System; public class Boiler { // Boiler class here } public class BoilerEventSink { public void BoilerTempoMeter(int temp) { if (temp <= 0) { Console.WriteLine("Alarm: Boiler is switched off"); } } } // Event caller mailn application public class BoilerCallerApp { public static int Main(string [] args) { Boiler boiler1 = new Boiler(); BoilerEventSink bsink = new BoilerEventSink(); Boiler.BoilerStatus += new Boiler.EngineHandler( bsink.BoilerTempoMeter); boiler1.SetBoilerReadings (55, 74); boiler1.SetBoilerReadings (0, 54); boiler1.SetBoilerReadings (8, 23); return 0; } } } As you can see in Listing 34, I created a Boiler object that calls the BoilerStatus handler, which passes BoilerEventSink’s methods as an argument when calling Boiler. EngineHandler is a delegate defined in the Boiler class. Then the program calls the SetBoilerReading method with different temperature and pressure reading. When the temperature is zero, the program displays a warning message on the console; otherwise, the program displays message generated by the SetBoilerReading method. Actually, it’s easier to understand events using windows application than it is using a console-based application. To show you can an event sample in windows Forms, you’ll create a Windows application. In this application, you’ll create a form and a button. The button-click event executes and displays a message box. Here, the button-click event executes button1_click method: button1.Click += new System.EventHandler(button1_ Click); and the button-click handler looks like the following: private void button1_click(object sender, System.EventArgs e) { MassageBox.Show ("button is clicked"); } Listing 35 shows a windows forms program with event sample. If you compile this program, the out put looks like figure 8. Listing 35. Event Handling example using System; using System.Windows.Forms; using System.Drawing; namespace NotePadWindowsForms { public class NotePadWindowsForms: System.Windows.Forms.Form { private System.Windows.Forms.Button button1; public NotePadWindowsForms() { button1 = new System.Windows.Forms.Button(); // Button control and its properties button1.Location = new System.Drawing.Point(8, 32); button1.Name ="button1"; button1.Size = new System.Drawing.Size(104,32); button1.TabIndex = 0; button1.Text = "Click me"; // Adding controls to the form Controls.AddRange(new System.Windows.Forms.Control[] {button1} ); button1.Click += new System.EventHandler(button1_Click); } // Button click handler private void button1_Click(object sender, System.EventArgs e) { MessageBox.Show ("Button is clicked"); } public static int Main() { Application.Run(new NotePadWindowsForms()); return 0; } } } Figure 8 shows the output of listing 35 after clicking the Click me button. Figure 8 output of listing35 14. Indexers Indexers are a new concept in C#. Indexers enable a class object to function as an array. Implementing indexers is similar to implementing properties using the get and set functions. The only different is that when you call an indexer, you pass an indexing parameter. Accessing an indexer is similar to accessing an array. Indexers are nameless, so the this keyword declares indexers. I just said that after defining indexers, a class object could be treated as an array. What does that mean? To explain, I‘ll show you an example using the class called my class. The way you treat an instance of myClass now is like this: myClass cls = new myClass(); cls.MaleGender = true; After defining an indexer in myClass, you could treat an instance of it as if it were an array: myClass cls = new myClass(); cls[0].MaleGender = true; cls[1].MaleGender = true; You define indexer by using the this keyword as if were an array property of type object. Listing 36 shows the indexer signature of my class. Listing 36. Indexers of myClass public object this[int index] { get { if (! ValidIndex(index)) throw new Exception("Index out of range."); else return MaleGender(index).Value; } set { if (!ValidIndex(index) ) throw new Exception("Index out of range."); else MaleGender(index).Value = value; } } 15. Inheritance Inheritance is one of the main features of an object-oriented language. C# and the .NET class library are heavily based on inheritance. The telltale sign of this is that all .NET common library classes are derived from the object class, discussed at the beginning of this article. As pointed out, C# doesn’t support multiple Inheritance. C# only supports single inheritance; therefore, all objects are implicitly derived from the object class. Implementing inheritance in C# is similar to implementing it in C++. You use a colon (:) in the definition of a class to derive it from another class. In listing37, BaseClassB, which later accesses the BaseClassA method in the Main method. Listing 37. Inheritance example using System; // Base class A class BaseClassA { public void MethodA() { Console.WriteLine("A Method called"); } } // Base class B is derived from Base class A class BaseClassB:BaseClassA { public void MethodB() { Console.WriteLine("B method called"); } } class myClass { static void Main() { // Base class B BaseClassB b = new BaseClassB(); // Base class B method b.MethodB(); // BaseClassA Method through BaseClassB b.MethodA(); } } Note: The below sections will be updated in next version. 16. C# 2.0 Features Here is a list of new features added to C# version 2.0. 1.Partial Classes 2.Static Classes 3.Property Accessor Accessibility Modifier 4.Nullable Types 5.Generics 6.Anonymous Methods 7.Iterators 8.Friend Assemblies 1. Partial Classes Partial classes is one of the coolest feature added to C# language. Having partial classes in the language provides programmers to write cleaner interfaces. A partial class means "A single class can be defined in multiple physical files.". For example, I can have a ClassA, which is defined in three different AFile.cs, BFile.cs, and CFile.cs physical files. Now you may ask why would I want that? Do you remember ASP.NET or Windows Forms applications, where designer (Visual Studio IDE) generated code was written in a region and your code will be added after that. When writing larger user interface driven applications (for example Windows UI or Web UI), you may want to have user interfaces related code in a file, some logic in a separate file and so on. Now using partial classes, we can have designer generated code in a separate file, control event handlers in a separate file, and rest of the code in a separate file. 2. Static Classes C# 2.0 now supports static classes. Here are static classes properties. A static class cannot be instantiated. That means you cannot create an instance of a static class using new operator. A static class is a sealed class. That means you cannot inherit any class from a static class. A static class can have static members only. Having non-static member will generate a compiler error. A static class is less resource consuming and faster to compile and execute. Public static class MyStaticClass { Private static int myStaticVariable; Public static int StaticVariable; { Get { return myStaticVariable; } Set { myStaticVariable = value; } } Public static void Function() { } } 3. Property Accessor Accessibility Modifier C# 2.0 supports access modifiers for property accessor, which means now you can set access levels to get and set accessors of a property. For example, I can write a property something like this: public string LoginName { get { return loginName; } protected set { loginName = value; } } So now I can set LoginName property from any class derived from the class that has this property but I won't be able to set this property from other classes. This feature was not supported in previous version of C#. I create a class called ABaseClass, which has LoginName property: class ABaseClass { ///
/// Property Access Modifiers
///
private string loginName;
///
/// Login Name
///
public string LoginName
{
get { return loginName; }
protected set { loginName = value; }
}
}
Now I create a new class, which is derived from ABaseClass and in this class I set set LoginName property.
class ADerivedClass : ABaseClass
{
public void SetPrivateProperty()
{
base.LoginName = "mcb";
}
}
If I try to set the property value from other classes, I get the following error:
4. Nullable Types
One of the new features of C# 2.0 is nullable types. Now C# 2.0 allows you to assign null values to premitive types such as int, long, and bool.
The following code shows how to define an integer as nullable type and checks if the value of the integer is null or not.
///
/// Nullable types
///
public static void TestNullableTypes()
{
// Syntax to define nullable types
int? counter;
counter = 100;
if (counter != null)
{
// Assign null to an integer type
counter = null;
Console.WriteLine("Counter assigned null.");
}
else
{
Console.WriteLine("Counter cannot be assigned null.");
Console.ReadLine();
}
If you remove the "?" from int? counter, you will see a warning as following:
17. C# 3.0 Features
Updates will be in next version.
Summary
This article offered an overview of the new Microsoft language, C#. C# takes the best features of many present day programming languages. You became familiar with some of the language’s syntax. You learned how to write and compile your first command-line program with the “Hello, C# World!” example. You also became familiar with classes and their members, their scopes, and how to use them. You learned about some unique features, such as events the indexers, which were not available in languages such as C++. In the end of this article, you also saw the new advanced features added to version 2.0 and 3.0.
Subscribe to:
Posts (Atom)