3. EVOLUTION OF C#
• C# is a new computer-programming language developed by
Microsoft corporation, USA
• C# is a fully object oriented language (like java) and first
Component-oriented language
• C# is a brand new language
derived from the C / C++ family
• C# is the only language designed
for the .NET Framework
• C# combines the best features of
many commonly used languages:
the productivity of Visual Basic,
the power of C++ and the
elegance of Java
4. EVOLUTION OF C#
• World Wide Web is increasing exponentially. The Internet is the
mainstream of many business organizations today.
• So the Microsoft Chairman Bill Gates wanted to develop a software
platform which will overcome these limitations and enable users to
get information anytime and anywhere, using a natural interface.
• The platform should be a collection of readily available Web services
that can be distributed and accessed via standard Internet protocols.
The outcome is a new generation platform called .NET.
• .NET is simply the Microsoft's vision of 'software as a service’.
• .NET platform began in the mid-90s, only during the Microsoft
Professional Developers Conference in September 2000, was .NET
officially announced to the developer community.
• At the same conference, Microsoft introduced C# as a de facto
language of the .NET platform.
5. EVOLUTION OF C#
• C# supports key features of .NET natively. They are
fairly tightly tied together. In fact, C# compiler is
embedded into .NET
• Like Java, C# is a descendant of C++ which in turn is a
descendant of C as illustrated in Fig. 1.3. C is the
mother of all the three modern languages.
• C# modernizes C++ by enhancing some of its features
and adding a few new features so as to help
developers do more with fewer lines of code and
fewer opportunities for error.
• C# borrows Java's features such as grouping of
classes, interfaces and implementation together in
one file so that programmers can edit the code more
easily. C# also handles objects using references, the
same way as Java.
• C# uses VB's approach to form design, namely,
dragging controls from a tool box, dropping them
onto forms, and writing event handlers for them.
6. CHARACTERISTICS OF C#
Simple
• C# simplifies C++ by eliminating irksome operators such as ->,:: and pointers. C# treats
integer and Boolean data types as two entirely different types. This means that the use
of = in place of = = in if statements will be caught by the compiler
Consistent
• C# supports an unified type system which eliminates the problem of varying ranges of
integer types. All types are treated as objects and developers can extend the type
system simply and easily
Modern
• C# is called a modem language due to a number of features it supports. It supports
• Automatic garbage collection • Modern approach to debugging
• Rich intrinsic model for error handling • Robust security model
• Decimal data type for financial applications
Flexible
• C# does not support pointers, we may declare certain classes and methods as 'unsafe'
and then use pointers to manipulate them. However, these codes will not be type-safe.
Inter-
operability
• C# provides support for using COM(Component Object Model) objects, no matter what language was
used to author them.
• C# also supports a special feature that enables a program to call out any native APL(Application
Program Language)
7. CHARACTERISTICS OF C#
Object-
oriented
• C# is truly object-oriented. It supports all the three tenets of object-oriented systems
• Encapsulation • Inheritance • Polymorphism
• The entire C# class model is built on top of the Virtual Object System (VOS) of the .NET
Framework. In C#, everything is an object. There are no more global functions, variables
and constants.
Compati-
ble
• C# enforces the .NET common language specifications and therefore allows inter-
operation with other .NET languages.
•C# provides support for transparent access to standard COM and OLE(Object Linking &
Embedding) Automation. C# also permits interoperation with C-style APIs.
Version
-able
• Making new versions of software modules work with the existing applications is known
as versioning. C# provides support for versioning with the help of new and override
keywords.
• With this support, a programmer can guarantee that his new class library will maintain
binary compatibility with the existing client applications.
Type-
Safe
• Type-safety promotes robust programs
• All dynamically allocated objects and arrays are initialized to zero
• Use of any uninitialized variables produces an error message by the compiler
• Access to arrays are range-checked and warned if it goes out-of-bounds
• C# does not permit unsafe casts
• C# enforces overflow checking in arithmetic operations
• Reference parameters that are passed are type-safe
• C# supports automatic garbage collection
8. APPLICATIONS OF C#
• C# is a new language developed exclusively to suit the features
of.NET platform.
• It can be used for a variety of applications that are supported
by the .NET platform:
Console applications
Windows applications
Developing Windows controls
Developing ASP.NET projects
Creating Web controls
Providing Web services
Developing .NET component library
9. C# DIFFER FROM C++
C# compiles straight from source code to executable code, with no object files.
C# classes are defined and implemented in the same place and therefore there is no
need for header files.
In C#, class definition does not use a semicolon at the end.
The first character of the Main( ) function is capitalized. The Main must return
either int or void type value.
All data types in C# are inherited from the object super class and therefore they are
objects.
In C#, data types belong to either value types (which are created in a stack) or
reference types (which are created in a heap).
C# checks for uninitialized variables and gives error messages at compile time. In
C++, an uninitialized variable goes undetected thus resulting in unpredictable
output.
C# supports a native Boolean data type and bool-type data cannot be implicitly or
explicitly cast to any data type except object.
Variable scope rules in C# are more restrictive. In C#, duplicating the same name
within a routine is illegal, even if it is in a separate code block.
Destructors in C# behave differently than in C++.
In C#, we cannot access static members via an object, as we can in C++.
C# does not support multiple code inheritance.
10. C# DIFFER FROM JAVA
C# uses .NET runtime that is similar to Java runtime, the C# compiler produces an
executable code.
C# has more primitive data types. Unlike Java, all C# data types are objects.
Arrays are declared differently in C#.
C# classes are quite similar to Java classes, there are a few important differences
relating to constants, base classes and constructors, static constructors, versioning,
accessibility of members etc.
Java uses static final to declare a class constant while C# uses const.
C# supports the struct type and Java does not.
Java does not provide for operator overloading
In Java, class members are virtual by default and a method having the same name in
a derived class overrides the base class member. In C#, the base member is required
to have the virtual keyword and the derived member is required to use the override
keyword.
C# provides built-in delegates and events. Java uses interfaces and inner classes to
achieve a similar result.
In Java, parameters are always passed by value. C# allows parameters to be passed
by reference by using the ref keyword.
In Java, the switch statement can have only integer expression, while C# supports
either an integer or string expressions.
There is no labeled break statement in C#. The goto is used to achieve this.
11.
12. UNDERSTANDING .NET:
THE C# ENVIRONMENT
• Microsoft wanted to make the World Wide Web (WWW) more
vibrant by enabling individual devices, computers and web
services to work together intelligently to provide richer
solutions to users.
• Microsoft calls this Web services' and the software strategy
for implementing and delivering these services is '.NET'.
• .NET is a software framework that includes everything
required for developing software for web services.
• Microsoft took many of the best ideas in the industry, added
their own creativity and innovations and produced a coherent
systems solution popularly known as Microsoft .NET.
• The Microsoft .NET software solution strategy includes three
key approaches as shown in Fig. 2.1.
13. UNDERSTANDING .NET:
THE C# ENVIRONMENT
• Microsoft .NET platform includes the following
components that would help develop a new
generation of smart Internet services:
.NET infrastructure and tools
.NET user experience
.NET building block
.NET device software
• Microsoft.NET products and services consist of the
following:
Windows .NET
MSN .NET
Office . NET
Visual Studio .NET
Personal subscription services
bCentral for .NET
• Third-party .NET services will provide opportunities
to a vast range of developers and users to produce
corporate and vertical services using .NET platform.
14. .NET STRATEGY & ORIGIN
• Three significant phases of development: OLE
technology, COM technology & .NET technology
1. OLE Technology
• OLE(Object Linking and Embedding) technology
was developed by Microsoft in the early 1990s to
enable easy inter-process communications.
• OLE provided support to achieve the following:
To embed documents from one application into
another application
To enable one application to manipulate objects
located in another application
This enabled users to develop applications which
required inter-operability between various
products such as MS Word and MS Excel.
15. .NET STRATEGY & ORIGIN
2. COM Technology
• Till the advent of COM technology, the monolithic approach had been used
for developing software.
• But when programs become too large and complex, the monolithic
approach leads to a number of problems in terms of maintainability and
testing of software.
• To overcome these problems, Microsoft introduced the component-based
model for developing software programs.
• In the component-based approach, a program is broken into a number of
independent components where each one offers a particular service.
• Each component can be developed and tested independently and then
integrated it into the main system. This technology is known as the
Component Object Model(COM) and the software built using COM is
referred to as componentware.
• COM technology offers a number of benefits to developers and users.
reduces the overall complexity of software
enables distributed development across multiple organizations or
departments
enhances software maintainability
16. .NET STRATEGY & ORIGIN
3. .NET Technology
• .NET technology is a third-generation component model
• This provides a new level of inter operability compared to COM
technology
• COM provides a standard binary mechanism for inter-module
communication
• This mechanism is replaced by an intermediate language called
Microsoft lntermediate Language (MSIL) or simply IL in the .NET
technology.
• Various .NET-language compilers enforce inter-operability by compiling
code into IL, which is automatically compatible with other IL modules.
• An inherent characteristic of IL code is metadata.
• Metadata is data about data and describes its characteristics, including
data types and locations.
• IL allows for true cross-language integration. In addition to IL, .NET
includes a host of other technologies and tools that will enable us
develop and implement Web-based applications easily.
17. .NET FRAMEWORK
• The .NET platform provides a new environment for
creating and running robust, scalable and distributed
applications over the Web.
18. .NET FRAMEWORK
• The .NET Framework provides an environment for building, deploying and running web
services and other applications.
• It consists of three distinct technologies:
Common Language Runtime (CLR)
framework Base Classes
User and program interfaces (ASP.NET and Winforms)
• The CLR is the core of the .NET Framework and is responsible for loading and running
C# programs
• Base classes provide basic data types, collection classes and other general classes for
use by C# and other .NET languages.
• The top layer contains a set of classes for developing web services and to deal with the
user interface
19. COMMON LANGUAGE RUNTIME
• The Common Language Runtime, popularly known as CLR is the
heart and soul of the .NET Framework
• CLR is a runtime environment in which programs written in C# and
other .NET languages are executed.
• It also supports cross-language interoperability.
• The CLR provides a number of services that include:
Loading and execution of programs
Memory isolation for applications
Verification of type safety
Compilation of IL into native executable code
Providing metadata
Memory management (automatic garbage collection)
Enforcement of security
Interoperability with other systems
Managing exceptions and errors
Support for tasks such as debugging and profiling
20. COMMON LANGUAGE RUNTIME
• Figure 2.6 shows a flow chart of CLR
activities that go on when an application
is executed.
• The source code is compiled to IL while
the metadata engine creates metadata
information
• IL and metadata are linked with other
native code if required and the resultant
IL code is saved
• During execution, the IL code and any
requirement from the base class library
are brought together by the class loader.
• The combined code is tested for type-
safety and then compiled by the JIT(Just
In Time) compiler to produce native
machine code, which is sent to the
runtime manager for execution.
21. COMMON LANGUAGE RUNTIME
1. Common Type System (CTS)
• The .NET Framework provides multiple language support using
the feature known as Common Type System that is built into
the CLR
• The CTS supports a variety of types and operations found in
most programming languages and therefore calling one
language from another does not require type conversions.
• Although C# is specially designed for the .NET platform, we
can build .NET programs in a number of other languages
including C++ and Visual Basic.
22. COMMON LANGUAGE RUNTIME
2. Common Language Specification (CLS)
• The Common Language Specification defines a set of rules
that enables interoperability on the .NET platform
• These rules serve as a guide to third-party compiler designers
and library builders
• The CLS is a subset of CTS and therefore the languages
supporting the CLS can use each others' class libraries as if
they are their own.
• Application Program Interfaces (APIs) that are designed
following the rules of CLS can easily be used by all the .NET
languages.
23. COMMON LANGUAGE RUNTIME
3. Microsoft Intermediate Language (MSIL)
• MSlL, or simply IL, is an instruction set into which all the .NET
programs are compiled
• It is an assembly language and contains instructions for
loading, storing, initializing and calling methods.
• When we compile a C# program or any program written in a
CLS-compliant language, the source code is compiled into
MSIL.
24. COMMON LANGUAGE RUNTIME
4. Managed Code
• The CLR is responsible for managing the execution of code
compiled for the .NET platform
• The code that satisfies the CLR at runtime in order to execute
is referred to as managed code
• Compilers that are compatible to the .NET platform generate
managed code
• For example, the C# compiler generates managed code. The
managed code generated by C# (and other compilers capable
of generating managed code) is IL code. The IL code is then
converted to native machine code by the JIT (Just In Time)
compilers.
25. FRAMEWORK BASE CLASSES
• .NET supplies a library of base classes that we can use to
implement applications quickly
• We can use them by simply instantiating them and invoking
their methods or by inheriting them through derived classes,
thus extending their functionality
• Much of the functionality in the base framework classes
resides in the vast namespace called System
• We can use the base classes in the system namespace for
many different tasks including:
• Input / Output Operations • Windows messages
• String handling • Database management
• Managing arrays, lists, maps, etc • Evaluation of mathematical functions
• Accessing files and file systems • Drawing
• Accessing the registry • Managing errors and exceptions
• Security • Connecting to the Internet
• Windowing • And many more
26. USER & PROGRAMMEINTERFACES
• The .NET Framework provides the following tools for
managing user- and application interfaces:
• Windows forms • Console Applications
• Web forms • Web services
• These tools enable users to develop user-friendly desktop-
based as well as web-based applications using a wide variety
of languages on the .NET platform.
27. VISUAL STUDIO .NET
• Visual Studio.NET (VS.NET) supports
an Integrated Development
Environment (IDE) with a rich set of
features and productivity tools
• These features and tools allow
developers to build web applications
faster and easier
• Using web services and XML
regardless of the language chosen for
development, there is now one
environment to learn, configure and
use
• We need not have to switch back and
forth between environments to
build, debug and deploy our code
• VS .NET provides tools that extends
support to the development lifecycle.
• As shown in Fig. 2.7, it acts as a
foundation for the Lifecycle platform.
28. .NET LANGUAGES
• The .NET Framework is language neutral. Currently, we can
use a number of languages for developing .NET applications
• All .NET languages are not created equal. Some can use the
components of other languages, some can use the classes
produced in other languages to create objects, and some
languages can extend the classes of other languages using the
inheritance features of .NET
Native to .NET Third-party Languages
• C# (Specially created for
.NET)
• Visual Basic
• C++
• Jscript
• COBOL • SmallTalk
• Eiffel • Mercury
• Perl • Scheme
• Python
29. BENEFITS OF .NET
Microsoft has advanced the .NET strategy in order to provide a
number of benefits to developers & users
Simple & Faster systems development
Rich Object model
Enhanced built-in functionality
Many different ways to communicate with the outside world
Integration of different languages into one platform
Easy deployment and execution
Wide range of scalability
Interoperability with existing applications
Simple and easy-to-build sophisticated development tools
Fewer bugs
Potentially better performance
30.
31. OVERVIEW OF C# : INTRODUCTION
• Unlike C++, both Java and C# promote a
one-stop coding approach to code
maintenance. They group classes,
interfaces and implementations
together in one file so that
programmers can edit the code more
easily
• C# can be used to develop two
categories of programs, namely,
Executable application programs
Component libraries
• Executable programs are written to
carry out certain tasks and require the
method Main in one of the classes.
• In contrast, component libraries do not
require a Main declaration because they
are not standalone application
programs.
32. SIMPLE C# PROGRAM
• The best way to learn a new language like C# is to write a few
simple programs and execute them. This will enable us to
analyze and understand how C# programs work. This program
that displays a line of text.
• Let us discuss the program line by line and understand the
unique features that constitute a C# program.
33. SIMPLE C# PROGRAM
1.Class Declaration
• The first line
class SampleOne
• declares a class, which is an object-oriented Construct
• C# is a true object-oriented language and therefore,
'everything' must be placed inside a class.
• class is a keyword and declares that a new class definition
follows
• SampleOne is a C# identifier that specifies the name of the
class to be defined.
• A class is a template for what an object looks like and how it
behaves.
34. SIMPLE C# PROGRAM
2.The Braces
• C# is a block-structured Language, meaning code blocks are
always enclosed by braces { and }.
• Therefore, every class definition in C# begins with an opening
brace '{‘ and ends with a corresponding closing brace '}' that
appears in the last line of the program.
• This is similar to class constructs of Java and C++
• Note that there is no semicolon after the closing brace.
35. SIMPLE C# PROGRAM
3.The Main Method
• The third line
public static void Main( )
• defines a method named Main. Every C# executable program
must include the Main() method in one of the classes.
• This is the 'starting point' for executing the program.
• A C# application can have any number of classes but 'only one'
class can have the Main method to initiate the execution.
• This line contains a number of keywords: public, static and
void.
• This is very similar to the main of C++ and JavD.
• In contrast to Java and C++, Main has a capital, not lowercase
M.
36. SIMPLE C# PROGRAM
3.The Main Method
Meaning Purpose of keywords
public The keyword public is an access modifier that tells the C# compiler
that the Main method is accessible by anyone
static The keyword static declares that the Main method is a global one
and can be called without creating an instance of the class. The
compiler stores the address of the method as the entry point and
uses this information to begin execution before any objects are
created.
void The keyword void is a type modifier that states that the Main
method does not return any value (but simply prints some text lo
the screen)
37. SIMPLE C# PROGRAM
4.The Output Line
• The only executable statement in the program is
System.Console.WriteLine("C# is sharper than C++.");
• This has a striking resemblance to the output statement of Java and
similar to the printf () of C or cout<< of C++.
• Since C# is a pure object-oriented language, every method should be
part of an object. The WriteLine method is a static method of the
Console class, which is located in the namespace System. This line
prints the string
C# is sharper than C++.
• to the screen. The method WriteLine always appends a new-line
character to the end of the string. This means, any subsequent
output will start on a new line.
• Every C# statement must end with a semicolon. And also note that
there is no semicolon at the end of the class.
38. SIMPLE C# PROGRAM
5. Executing the program
• After creating the program (source code),
save it with .cs file extension in a folder in
your system. We may use 'any suitable
name' for the file. In this case, we may
use the class name itself. Example:
sampleone.cs
• For compiling the program, go to the
folder where you have stored the file
sampleone.cs and then type the following
command:
csc sampleone.cs
• The C# Compiler (CSC) compile your code
and create an executable file (IL code) by
name
sampleone.exe
• in the same directory
39. SIMPLE C# PROGRAM
5. Executing the program
• If there are errors, the compiler will produce appropriate error
messages. Errors should be corrected and the program should
be compiled again.
• For executing the program, simply type in the name of the
executable file at the command prompt. That is,
sampleone
• Note that no file extension is used. This will display the output
C# is sharper than C++.
on the screen
40. NAMESPACES
• Let us consider the output statement of the previous sample
program again:
System.Console.WriteLine( );
• System is the namespace (scope) in which the Console class is
located. A class in a namespace can be accessed using the dot
operator. Namespaces are the way C# segregates the .NET
library classes into reasonable groupings.
• C# supports a feature known as using directive that can be
used to import the namespace System into the program. Once
a namespace is imported, we can use the elements of that
namespace without using the namespace as prefix.
41. NAMESPACES
• First statement in the program is using System; This tells the compiler to
look in the System library for unresolved class names.
• When the compiler parses the Console.WriteLine method, it will
understand that the method is undefined. However, it will then search
through the namespaces specified in using directives and, upon finding
the method in the System namespace, will compile the code without
any complaint.
42. ADDING COMMENTS
• Comments play a very important role in the maintenance of programs.
They are used to enhance readability and understanding of code. All
programs should have information such as implementation details,
change history and tasks performed. C# permits two types of comments,
namely,
Single-line comments
Multiline comments
• Single-line comments begin with a double backslash ( //) symbol and
terminate at the end of the line. We can use // on a line of its own or
after a code statement. This can also be used to comment out an entire
line or part of a line of source code. Everything after the // on a line is
considered a comment.
• If we want to use multiple lines for a comment, we must use the second
type known as multi-line comment. This comment starts with the /*
characters and terminates with */. These comments can also occur
within a line. For example:
using /*namespace*/ System; //o.k
• Remember, we cannot insert a //-style comment within a line of code.
However, we can use the // style for commenting multi-lines.
43. ADDING COMMENTS
• This will cause an error because of a mismatch between the
starting and ending symbols. That is, we cannot nest the/* */
comments.
• Every /* symbol should have a corresponding */ symbol.
44. MAIN RETURNING A VALUE
• Another important aspect is the return type of Main( ). We have
used void as the return type in earlier programs. Main( ) can also
return a value if it is declared as int type instead of void. When the
return type is int, we must include a return statement at the end of
the method.
• Returns an integer-type value to the system.
• The value returned serves as the program's termination status code.
• The purpose of this code is to allow communication of success or
failure to the execution environment
45. COMMAND LINE ARGUMENTS
• There may be occasions when we may like our program to
behave in a particular way depending on the input provided at
the time of execution. This is achieved in C# by using what are
known as command line arguments.
• Command line arguments are parameters supplied to the
Main method at the time of invoking it for execution. This
program accepts a name from the command line and writes it
to the console.
46. COMMAND LINE ARGUMENTS
• Earlier examples, we have used the Main method with no parameters. Notice bow
the Main is declared in this example.
public static void Main (string[ ] args)
• Main is declared with a parameter args. The parameter args is declared as an array of
strings (known as string objects). Any arguments provided in the command line (at
the time of execution) are passed to the array args as its elements. We can access the
array elements by using a subscript like args[0], args[1] and so on. For example,
consider the command line
SampleSix C sharp
• This command line contains two arguments which are assigned to the array args as
follows:
C - args [0]
sharp - args [1]
• Note that C# subscripts begin with 0 and not 1. We will get the following output:
Welcome to C sharp
• Its only difference from the WriteLine () method is that Write () does not cause a line
break and therefore the next output statement is printed on the same line. Thus, all
the three output statements combine to produce one line of output.
• The output statements concatenate strings using the+ operator while printing. Here,
empty strings are used to provide blank space between strings.
47. MAIN WITH A CLASS
• Let us add a simple class to the class containing the Main
method.
48. MAIN WITH A CLASS
• This program has two class declarations, one for the TestClass and
another for the Main method.
• TestClass contains only one method to print a string "C# is modern".
The Main method in SampleSeven class creates an object of
TestClass and uses it to invoke the method fun () contained in
TestClass as follows:
TestClass test = new TestClass ( );
test.fun ( );
• The object test is used to invoke the method fun() of TestClass with
the help of the dot operator
• Execution of Program will produce the following output:
C# is modern
• If we want, we could include the TestClass declaration within the
class SampleSeven. That would mean creation of 'nested' classes.
49. PROVIDINGINTERACTIVEINPUT
• Two approaches for giving values to string objects:
Using an assignment statement
Through command line arguments
• To give values to string variables interactively through the
keyboard at the time of execution
• This program shows how to get specific information from the
user and print a message using that information.
50. PROVIDINGINTERACTIVEINPUT
Console.Write("Enter your name: ");
• outputs the message "Enter your name:" and the method
Console.ReadLine( );
• causes the execution to wait for the user to enter his name.
• The moment the user types his name and presses the 'Enter' key, the input is read into the
string variable name.
• The second output line (WriteLine method) concatenates the name-string with 'Hello' and
presents the resultant string to the user. The output will look like this:
Enter your name: John
Hello John
• Change the contents of Main as shown below and try executing the program.
public static void Main( )
{
Console.Write ("What is your name?");
string s;
s =Console.ReadLine( );
Console.writeLine("Hello,"+ s)
Console.Write("What is your age?");
s =Console.ReadLine( );
Console.WriteLine("You look nice at"+ s);
}
Output:
What is your name? John
Hello John
What is your age? 35
You look nice at 35