c#-unit-1
c#-unit-1
Evolution of .Net:-
At the time of mid ninety, java has been so popular to develop the
application because of its platform independent technique and open source policy if
sun Microsystems. Around 2002, Sun Microsystems has introduced the Java 2
Enterprise Edition (J2EE)to create the distributed application. This means, the
functioning of an application is distributed on several computers based on the N-tier
architecture. This feature of J2EE eventually led to the decline of, Microsoft’s
market share. Consequently, Microsoft started a project called Next Generation
Windows Services (NGWS) to regain the market share. It took more than three
year to develop the product, which is known as .Net.
Microsoft released the first version of .Net with the name .Net Framework 1.0
in February 13, 2002, along with the Visual Studio .Net 2002 integrated
development environment (IDE). .Net’s second version took nearly a year to
release, and was known as .Net framework 1.1 Microsoft Visual Studio .Net, better
known as Visual Studio .Net 2003, was also a part if the second release. The next
version of .Net framework, .Net framework 2.0, was released with Visual Studio
.Net 2005 on November 07, 2005.
1
Then, .Net framework 3.0, formerly called WinFX, was release on November
06, 2006. Finally latest version of .Net Framework, known as .Net framework 3.5,
was released with Visual Studio .Net 2008 on November 19, 2007.
2
Advantages of .Net Framework:-
The .Net framework offers many benefits to application developers. Some of
these benefits are as follows;
1). Consistent programming model:-
.Net framework provides a consistent object-oriented programming model
across different languages. We can use this model to create programs for
performing different tasks, such as connecting to and retrieving data from
databases, and reading from and writing to the files.
3
Fig:-
.
Components of .Net Framework 3.5:-
As shown in Fig .Net framework 3.5 is based on .Net framework 2.0 and
.Net framework 3.0; therefore, .Net framework 3.5 includes several
components that are part of .Net Framework 2.0 and .Net framework 3.0.
Following are some of the essential as well as new components of .Net
framework 3.5:
1). Common Language Runtime(CLR)
2). The .Net framework Class Library
3). Common Language Specification (CLS)
4). Common Type System(CTS)
5). Metadata and Assemblies
6). Windows Forms
7). ASP.Net and ASP.Net AJAX
8). ActiveX Data Object for .Net (ADO.NET)
9). Windows Workflow Foundation (WF)
10). Windows Presentation Foundation (WPF)
11). Windows Communication Foundation (WCF)
12). Windows CardSpace(WCS)
13). LINQ
For the jobs and details of each components;
4
1). Common Language Runtime(CLR):-
One of the most important components of .Net Framework is the CLR, better
known as the runtime. It provides functionalities such as memory management,
exception handling, debugging, security, thread execution, code execution, code
safety, verification, compilation, and so on. It also supports versioning to any
language that the CLR interacts with.
This indicates that the CLR can host a variety of languages and provide
common tools to these languages. This ensures interoperability between the codes,
such as Visual c#, Visual Basic, or Visual c++ by providing a common environment
for the execution of code written in any of these languages.
Fig:- (Functioning of CLR)
The code that is executed directly by the CLR is known as managed code,
whereas the code that cannot be directly executed by the CLR is known as
unmanaged code. When we run a .Net application, the language compiler first
compiles the source code into an intermediate code called Microsoft Intermediate
Language (MSIL) code. The MSIL code is then used by the Just-In-Time (JIT)
compiler to convert the MSIL code into the native machine code, which is the final
executable code. The CLR also provides automatic memory management for .Net
applications. The managed environment of the runtime eliminates many common
software issues, such as memory leaks and invalid memory references. The CLR
uses the garbage collector to manage the allocation and release of memory for an
application. CLR also supports services that the application uses to access various
resources such as collections, arrays, operating system folders, and so on.
5
2). The .Net Framework Class Library:-
.Net Framework consists of classes, interfaces, and value types that help in
speeding up the development process and provide access to system functionality.
Or we can easily say that .Net Framework Class Library is a huge library of reusable
types for use by managed codes.
It is an object oriented library that is used in component- based applications.
The FCL is made up of a hierarchy of namespaces.
Each namespaces contains classes, structures, interfaces, enumerations, and
delegates. The namespaces are logically defined by their functionality. For example,
the System.Data namespace contains all the functionality available for accessing
databases. This namespace is further broken down into System.Data.SqlClient,
which exposes the functionality specific to Structured Query Language (SQL)
Server, and System.Data.OleDB, which exposes functionality required to work with
Object Linking and Embedding Database (OLE DB)data sources. When using the
FCL., remember the succeeding points:
1). The classes, interface, structures, and enumerated vales are collectively
referred to as types.
2). The different types in the framework are arranged in a hierarchy of
namespaces. This solves the problem faced in name collisions.
Namespaces are arranged in a hierarchy having words separated by
periods.
3). The System namespace is the root namespace for fundamental types in
.Net Framework. This namespace includes classes that represent the
base data types used by all applications, such as object, Byte, Char,
Array, Int32, String, and so on.
4). All types must have a base class including user-defined types. The
exception to this rule is the Sytem.Object type, which is the base type for
all types in the .Net framework.
6
4). 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 conversations.
The CTS specifies certain guidelines for declaring, using and managing types
at runtime. It is an integral part of the runtime for supporting cross- language
communications. The functions performed by CTS are;
1). Helps in cross-language communication, type safety, and high performance
execution of code by establishing a framework.
2). Supports object-oriented model for implementation of different programming
languages.
3). Specifies guidelines for different languages to follow, ensuring proper interaction
between objects of different languages.
Classification of Types:-
The CTS can be classified into two general categories of types which are
further divided into subcategories value types and reference types;
1). Value Types:-
Contain their data directly and their objects that are allocated on the stack.
Value types can be built –in, user defined or enumerations.
2). Reference Types:-
Contain the reference of the data’s memory address and are allocated in a
heap. They can be pointer types, interface types, or self- describing types. The self
describing types can be arrays and class types.
7
5). Metadata and Assemblies:-
A metadata describes a program that is in the form of binary information
stored in a CLR portable executable (PE) file or in the memory. When compilation of
the code takes place in a PE file, the metadata is inserted into one part of the file,
while the code is converted into IL and inserted into the other part of the file. The
metadata describes every types and member. When the code is in the run mode,
the CLR loads the metadata into the memory and finds information about the code’s
classes, members and so on.
8
1). Assembly information, such as its identity which can be a name, version,
culture, public key, the types of assemblies, other referenced assemblies, and
security permissions.
2). Information about types, such as name, visibility, base class, interfaces used,
and members (methods, fields, properties, events, nested types)
3). Maintains the attribute information which modifies the types and members of a
class.
After providing the listed information, CLR is able to create objects, access
data and call member functions. In .NET every application is compiled into an
assembly, which forms the unit of deployment, versioning, code reuse, and security
of the application, This implies that everything we do in an application occurs in the
scope of an assembly.
The assembly metadata is the metadata about the assembly itself and its
components, while the type metadata is the metadata about the types such as
classes, interfaces, structures, and so on. A single assembly can contain multiple
code files or a single code file can have more than one assembly. An assembly
9
contains code which the CLR executes.
10
It enables us to send only the modified portions of a web page to the web server by
making asynchronous calls to the web server. This decreases network traffic as well
as processing on the web server.
3). Scalability:-
ADO.NET helps in scalability while working with datasets. All database
operations are performed on the dataset instead of on the database. This reduces
the traffic on the database and saves the resources resulting in more efficiency of
the database in meeting the demands of the user.
11
9). Windows Workflow Foundation:- (WF)
Windows Workflow Foundation (WF) is a technology introduced by Microsoft
which provides a programming model, for building workflow based applications on
Windows. It includes activities, workflow runtime, workflow designer, and a rules
engine. WF is a part of .NET Framework 3.0 and 3.5. The most important feature of
WF is the separation between the business process code and the actual
implementation code. Before WF was introduced, it was a practice to write both the
business logic and the actual implementation code together as in Visual c#, Visual
Basic or any other .NET language. Now, we can say that ‘what is done’ is defined in
the WF and ‘how it is done’ was defined in the traditional programming code.
12
10). Windows Presentation Foundation:-
Micorsoft’s Windows Presentation Foundation (WPF) provides the base for
building applications and a clear separation between the user interface and the
business logic. Although Windows Forms Application have a rich user interface(UI),
it required various APIs for working with documents, such as Microsoft word or PDF
files, videos, two dimensional and three dimensional images and multimedia. It
helps in creating Windows client applications with visually stunning user
experiences. We can use WPF for creating both standalone and browser hosted
applications. Example of WPF applications are the Yahoo Messenger, the New York
Times Reader, and the Contoso Healthcare Sample Application.
WPF introduces a new language called XAML( eXtensible Application Markup
Language), which is a language based on XML. Both designers and developers can
easily and efficiently work and collaborate on the development process of WPF
application.
13
Fig:- WCF architecture
13). LINQ:-
Language Integrated Query (LINQ) is one of the components of
Microsoft.NET Framework 3.5 that adds native data querying capabilities to .NET
languages using a syntax similar to SQL. This implies that with LINQ, we can write
statements similar to SQL statements in a .NET language, such as Visual C#. With
LINQ, we can query SQL server databases, datasets, objects in a collections and
XML documents.
Terms:-
1). MSIL :- (MicoroSoft Intermediate Language)
MSIL is also known as CIL ( Common Intermediate Language) or IL
(Intermediate Language). It contains instructions for loading, storing, initializing
and calling methods of objects. MSIL is the CPU independent instruction set into
which .NET Framework programs are compiled.
14
2). JIT:- (Just In Time)
It is a smart compiler. JIT does not compile while program each and every
time. It compiles only that portion of the program which functions are called that
time and suppose native code is already present then that data will not again
compiled. If changes are made then possible that it will again generates MSIL to
Native.
VISUAL STUDIO 2008
Introduction:-
Microsoft Visual Studio is an Integrated Development Environment (IDE)
provided by Microsoft to create and develop Windows-based, Web-based, Console-
based and Mobile-based applications for .NET Framework. These applications might
be created by using different languages such as Visual Basic, Visual C#, and Visual
c++. Traditionally, we created these applications using a Notepad. For this, we
need a compiler that could convert the programming language into machine
language.
Now, we might be wondering if a Notepad can create all these applications,
why do we need Visual Studio as an editor? Building applications using Notepad
would take much time than building the same applications in Visual Studio. This is
because Microsoft Visual Studio provides various benefits to design and create the
applications, as compared to a notepad. For example, we need to memorize all the
language syntax I case we are using a Notepad. In case of Visual Studio, we do not
need to remember the syntax, we need to type the first few letters of a command
and Visual Studio would prompt us with the available options for the command.
The following are some of the benefits of using Visual Studio 2008.
Helps in minimize the development time
Simplifies the process of testing application.
Provides different toolsets for integrating graphic designers into the overall
development process
Supports multiple versions of the .NET Framework
Enhancements in data retrieval and data binding
Inspects code to find sections of code that need to be refactored
Provides support for web, mobile, client Vista and office application
development
Integrates with the .NET Framework 3.5
15
Let’s explore each of these in detail;
16
Report Wizard:-
Visual Studio 2008 provides a Report Wizard, which guides us through a
number of steps to create a basic report.
Expression Editor Enhancement:-
The Expression Editor provides sample expressions that we can directly use
in our report or customize it according to our requirement.
Report Viewer Printing:-
When we configure the ASP.NET Report Viewer control for local processing,
the RSClientPrint control becomes available.
PDF Compression:-
The Report Viewer controls can now compress reports that have seem
rendered or exported to the PDF format.
17
4). Visual Studio Team System:-
Visual Studio Team system includes a set of software development and
reporting tools, in addition to the features provided by Visual Studio Professional
edition. It offers the following toolsets based o the development role; it is being
used for;
Team Explorer
Architecture Edition
Database Edition
Development Edition
Test Edition
It is designed for full programming staffs in large corporations.
Types of Project:-
Before moving on, let us mention briefly all the types of projects we can build
with Visual Studio 2008. The following are some of the different projects that can
be created with Visual Studio .Net 2008.
1). Console Application
2). Windows Application
3). Windows Services
4). Web Application
5). Web Services
6). Class Library
7). Windows Control Library
8). Web Control Library
9). Setup
Describe each type in detail;
1). Console Application:-
Console applications are light weight programs run inside the Command
Prompt (DOS) window. This type of application displays its output on a Command
Prompt window and receives input from the same window.
18
Console applications refer to those .net applications that do not have
graphical user interface except for a command line console. This makes console
applications suitable for situations where user interaction is not required.
19
9). Setup and Deployment:-
Visual studio provides templates for deployment desktop, web and smart
device setup and deployment projects. Different versions of the development
environment may support setup and deployment for some or all of the c#
application types on the desktop, on the web, and for mobile devices.
Introduction of C#:-
Programming languages have strengths in different areas. Some languages
are powerful but can be bug-prone and difficult to work with, while others are
simpler but can be limiting in terms if functionality or performance. There are so
many languages available these days but people definitely are going for languages
that involve less coding and at the same time can develop applications in a visually
powerful environment. C# (pronounced C-Sharp) is no doubt the language of
choice in the .Net environment. It is a whole new language free of the backward
compatibility curse with a whole bunch of new, exciting and promising features. It
is an Object Oriented Programming language and has at its core, many similarities
to Java, C++ and VB. In fact, c# combines the power and efficiency of c++, the
simple and clean OO design of Java and the language simplification of Visual Basic.
C# is one of those languages that involve less of coding and are rich in
graphical user interface. C# is a high level programming language, which means it
is easy to learn and understand unlike low level programming language that
involves creating applications in the machine language. C# includes all the support
for structured, component based, object oriented programming that one expects of
a modern language built on the shoulders of c++ and Java. C#.NET is evolving
faster day by day. The C# language was developed by a small team led by two
distinguished Microsoft engineers, Andes Hejlsberg and Scott Wiltanuth. Hejlsberg
is also known for creating Turbo Pascal, a popular language for PC programming,
and for leading the team that designed Borland Delphi, one of the first successful
integrated development environments for client/server programming. Anders
Hejlsberg was a Java Expert, it is natural that many java features have been
incorporated into the design of c#. In fact, in many cases, the c# code may bear a
striking resemblance to the functionally equivalent java code. 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 programs can
edit the code more easily.
C# can be used to develop two categories of programs, namely,
1). Executable application programs
2). 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. They are
written for use by other applications. This concept is something similar to applets
and application programs in Java.
20
Features of C#:-
C# 2008 has been greatly improved for C# developers as it now includes
new compiler features, new language constructs and improved debugging. In C#
2008, varieties of new features have been added to increase the productivity of c#
developers. These new features help the developers to create c# applications easily
and efficiently. Following are the list of new features added to c# 2008.
1). Implicitly Typed local variables
2). Auto implemented Properties
3). Extension Methods
4). Query Keywords
5). Partial Method Definition
6). Object and Collection Initializers
7). Anonymous Types
8). Lambda Expressions
Discuss all these new features one by one.
21
In this example, a simple class having three auto –implemented properties.
No, Name and Rno. The properties Rno is compiled as read-only properties because
their set accessors are assigned as private.
22
5). Partial Method Definition:-
while working on a large project, there are times when we need to split the
definition of a class, a struct, an interface, or a method over two or more source
files. Each source file should contain a section of the class or method definition, and
when we compile the application; the compiler combines all the source files.
Splitting and combining a large project helps a group of programmers to work on a
single class of the large project simultaneously. We cam use the partial keyword to
split a class definition. The partial keyword determines that the other source files
of the class, interface, struct or method can be defined in the namespace. However,
note that all the source files must use the partial keyword and be available while
compiling to form final type. Moreover, all the source files must use the same
access modifiers, such as private and public.
E.g:-
Let’s take an Motor class, which contains two subclasses named
MachineryParts and BodyParts. With the Motor class, we create two source files;
one for MachineryParts and another BodyParts, using the partial modifier. When we
compile both the source files, they get combined into a single one. This means that
we have split the Motor class into two different subclasses to work simultaneously.
E.g:-
Public class company
{
public string name {get; set;}
}
public static void ObjectInitialize()
{
company c= new company {name=”Tanmay”}; //object initilizer
}
In the preceding code snippet, we have declared an automatic property,
named name. The value of the name property is assigned by creating an object of
the company class, say c, which does not explicitly create and invoke a constructor.
However, we can also use the object initializers in some other context. The
object initializers play an important role in Language Integrated Query (LINQ)
expressions. The LINQ expressions use a large number of anonymous types and
require the object initializers to initialize these anonymous types.
Collection initializers initialize a collection in a very easy way. They prevent
us from adding a similar line of code multiple times.
E.g:-
List <company> c= new List<company>
{
new company() {name=”Ananya”},
new company() {name=”Vaidehi”}
};
23
7). Anonymous Types:-
When we create properties for our applications, there are times when we
need to crate a few or more read-only properties. These read-only properties can
be encapsulated into a single unit by means of the anonymous types. The
anonymous types can encapsulate the read only properties, without explicitly
defining a type. The compiler generates the type name as required but this type
name is not available at the source code level. The type of the properties is derived
by the compiler. In other words, we can say that the anonymous types create
unnamed structure types that can be added to the collections and accessed by
using the var keyword.
The anonymous types are also called class types, having one or more public
read only properties. However, they do not use any other class members, such as
methods and events. We can use the new operator with the object initializer to
create an anonymous type.
E.g:-
var no= new {Roll= 13 , Name= “Tanmay”};
Data types:-
C# is a strongly typed and rich language; therefore every variable in C# is
associated with a data type. Data types specify the type of values that can be
stored in particular variable. There are a number f data types available in C#, which
allows a programmer to select the type appropriate to the requirement of the
application. From built in types, such as integers or strings or user defined types,
such as structures, enumerations and classes. When dealing with these data types,
remember the two facts about the C# environment:
i). All variables, whether user-defined or built in can be used as object anywhere in
the system.
ii). All variables in the system are automatically initialized to default values by the
system when they are declared.
Generally, the data types in C# are primarily categorized in three parts;
Value type, Pointer type and Reference type.
24
Discuss each type in detail;
We can further categorize value types in two parts; Struct and Enumeration
type.
i). Struct types:-
Struct types are a special form of classes having the properties of value
types. We know that the value types are stored I the stack; inherently the struct
types are also stored on the stack. Since stacks are the efficient and convenient
means storing and accessing the types than heap, the struct types can be copied
and created efficiently. We can find the default value for the struct type by the
value produced by setting all the value types to their default values and all
reference types to null. The struct types encapsulate small group f related
variables, such as name, roll no, age, class and so on of any student. Struct can
also have constructors, methods, properties, operators, events, nested types,
indexers, constants and fields. However, while creating a struct types, we should
remember that the struct members can not be declared as protected. While
declaring struct types, the fields can be initialized only when they are declared as
const or static.
25
Struct types are created using the struct keyword. When we create a struct
object and assign it to a variable, the variable holds the complete value of the
struct object. The struct type is a value type; so any changes in the new copy do
not affect the old copy. The struct types are categorized into the following five
categories:
• Integeral Type:-
C# uses a set of basic data types, which are known as integral type. This set
consists of the types, such as sbyte, byte, short, ushort, int, uint, long, ulong and
char. Integral types can hold whole numbers only.
• Floating point Type:-
The floating point types take the values in fractions. The floating point types are
divided into two types. Float and double
• Decimal Type:-
The decimal types are equivalent to a long integer that behaves as if it were a
floating point numbers. Decimal values are intended to be used for the calculations
in which truncation beyond precisions and smaller range. To specify a number as a
decimal type, we must append the character M to a value such as 123.45M. If we
omit M, the value is treated as double.
• Boolean Type:-
Boolean types are used to test a particular condition during the execution of
program. Boolean type takes only two values; true or false.
• Nullable Type:-
A programming language supports Nullable data types when dealing with
database or when a user does not want to assign a value to a variable of any type.
26
3). Reference Type:-
Reference types are of varied lengths and stored on the heap of memory. When
the value has to be assigned between two reference variables, only the reference is
copied and the actual value remains the same in the memory location. We can
further categorize the reference types into two parts; User defined and pre defined
types.
i). Predefined Types:-
Predefined types can be divided into main two types.
• Object Type:-
Object type is the ultimate base type of all the other predefined and user
defined data types in C#. We can use the Object type to convert a value type on a
stack into an object type to be place on the heap.
• String Type:-
String type is used for creating and manipulating strings in C#. We can
perform various operations on strings, such as copying, comparing, and
concatenating on these string objects.
27
Fig:- Actual storing method of value and reference types
C# tokens:-
A programming language is designed to manipulate certain kinds of data
consisting of numbers, characters and strings and provide useful output known as
information to the user. The task of manipulating data is accomplished by
executing a sequence of instructions constituting what is known as program.
A C# program is basically a collection of classes. A class is defined by a set of
declaration statement and method containing instructions known executable
statements. These instructions are formed using certain symbols and words
according to some rigid rules known as syntax rules or grammar.
28
The smallest, non-reducible, textual elements in a program are referred to as
tokens. The compiler recognizes them for building up expressions and statements.
In simple terms, a C# program is a collection of tokens, comments and white
spaces. C# includes the following five types of tokents;
1). Keywords 2). Identifiers 3). Operators
4). Punctuators 5). Literals
Let’s discuss each in detail;
29
Contextual Words:-
From Get Group Into Join Let Orderby Partial
(type)
Partial Select Set Value Where Where Yield
(method) (generic (query
type clause)
constraint)
Irrespective of using reserved keywords as identifiers, contextual keywords
can be used as identifiers outside the context it is limited. This means that the
contextual keywords can have special meanings in two or more contexts. C#
permits the use of keywords as identifiers when they are prefixed with the ‘@’
character.
2). Punctuators:-
Punctuators are symbols used for grouping and separating code. They define
the shape and function of a program. Punctuators are also known as separators in
c# include;
1). Parentheses () 2). Braces { }
3). Brackets [] 4). Colon :
5). Semicolon ; 6). Comma ,
7). Period .
3). Operators:-
Operators are symbols used in expressions to describe operations involving
one or more operands.
30
Scope Resolution Operator:-
The:: (scope Resolution) operator is added between two identifiers, and the left-
hand identifier of the :: operator is taken as a global identifier, or an extern, or
alias. When the left-hand identifier of the:: operator is global, the global
namespace is searched for the right hand identifier.
Type conversion:-
While writing C# applications, a programmer often needs to perform a typical
task, that is convert one data type into another type. It can be divided into two
types; implicit and explicit conversion.
31
1). Implicit Conversion:-
Implicit conversions are the conversions that the language does for us,
behind the scenes, in a type-safe manner. If a compiler converts one type of data
into another type of data automatically, it is known as implicit conversion.
32
Boxing and Unboxing:-
In object-oriented programming, methods are invoked using objects. Since
value types such as int and long are not objects, we cannot use them to call
methods. C# enables us to achieve this through a technique known as boxing.
Boxing means the conversion of a value type on the stack to a object type on the
heap(global). Conversely, the conversion from an object type back to a value type
is known as unboxing.
1). Boxing:-
Any type, value or reference can be assigned to an object without an explicit
conversion. When the compiler finds a value type where it needs a reference type,
it creates an object ‘box’ into which it places the value of the value type.
E.g:- int t=100;
Object ob_t=t; //creates an object to hold t
2). Unboxing:-
Unboxing is the process of converting the object type back to the value type.
Remember that we can only unbox a variable that has previously been boxed. In
contrast to boxing, unboxing is an explicit operation using C-style casting.
E.g:- int t=10;
Object ob_t=t; //as in above example
Int un_t=(int)t; //unbox ob_t to an int
When performing unboxing, C# checks that the value type we request is
actually stored in the object under conversion. Only if it is, the value is unboxed.
When unboxing a value, we have to ensure that the value type is large enough to
hold the value of the object. Otherwise, the operation may result in a runtime error.
Notice that when unboxing, we need to use explicit cast. This is because in the case
of unboxing, an object could be cast to any type. Therefore, the cast is necessary
for the compiler to verify that it is valid as per the specified value type.
C# Programming Structure:-
A C# program basically consists of the following parts:
1). A Namespace declaration
2). A class
3). Class Methods
4). Class Attributes
5). A Main method
6). Statements and Expressions
7). Comments
namespace template_class
{
33
class Program
{
static void Main(string[] args)
{
Console.WriteLine("National Computer College!!!");
Console.ReadKey();
}
}
}
The first line of the program using system: The using keyword is used to
include the system namespace in the program. A program generally has multiple
using statements. All the code we write exists within an implied namespace that
exists for the current context of our code. Wnother thing worth mentioning about
namespace is that they replace the c++ #include notation and are equivalent of the
import statement in Java. That is, with the use of the using keyword, we can tell
the compiler which namespaces and libraries of the code we want to use in the
system. The most common use of the using keyword is to include the system
namespace in our program.
The next line has the namespace declaration. A namespace is a
collection of classes. In the other word, the concept pf amespace is nor new to
c#. c++ has them, and hava has been using the same concept for a long time. A
namespace is a wrapper around one or more structural elements that make them
unique. This namespace can be implemented to wrap around all the classes defined
for a given company or corporation.
The next line has a class declaration, the class contains the data and method
definitions that our program uses. Classes generally would contain more than one
method. Methods define the behaviour of class.
The next line defined the Main method, which is the entry point for all C#
programs. The Main method states what the class will do when executed.
The comment /*….*/ will be ignored by the compiler and it has been put to
additional comments in the program.
The main method specifies its behavior with the statement
Console.WriteLine("National Computer College!!!"); Writeline is a method of the
Console class defined in the system namespace. This statement causes the
message “National Computer College” to be displayed on the screen.
The last line Console.Readkey(); is for the VS.NET users. This makes the
program wait for a key press and it prevents the screen from running and closing
quickly when the program is launched from Visual Studio.NET.
Variable name=console.ReadLine();
34
Conditional Statements:-
A C# program is a set of statements that are normally executed sequentially in
the order in which they appear. This happens when options or repetitions of certain
calculations are not necessary. We have a number of situations, where we may
have to change the order of execution of statements based in certain conditions, or
repeat a group of statements until certain specified conditions are met. This
involves a kind of decision- making to see whether a particular condition has
occurred or not and then to direct the computer to execute certain statements
accordingly. Through we can the control flow statements to make only specific
blocks of code to execute in the fulfillment of specific conditions. We can also use
the control flow statements to transfer the program control from one block to
another block.
There may arise a situation when our program is logically correct and compiled
successfully, but in fails to display the required output and terminates abruptly.
This kind of situation may arise due to an exception in our program. An exception is
an event that occurs during the execution of a program and disrupts the normal
flow. C# language possesses such decision-making capabilities and supports the
following statements are known as control flow or conditional statements;
1). If statements
2). Switch statements
let’s discuss each statement in detail;
1). If Statements:-
One of the most important and commonly used conditional statement is if
statement. The if statement is a powerful decision making statement and is used to
control the flow of execution of statements. In if statement, first check the
expression/ condition, if it returns true then evaluate the statements, which is
written within if.
Syntax:- if (Test Expression/condition)
{
//statements;
}
E.g:- static void main(string[] args)
{
int a = 50, b = 70;
if (a < b)
Console.WriteLine("A is less");
if (a > b)
Console.WriteLine("B is less");
if (a == b)
Console.WriteLine("Both are same");
Console.ReadKey();
}
If..else Statements:-
In if..else statements, first check the expression/condition, if it returns true
then evaluate the true block statements. Otherwise, evaluate the false block
statements.
35
Syntax:- if(test Expression/condition)
{
//true block statement
}
else
{
//false block statement
}
E.g:- static void main(string[] args)
{
int a = 50, b = 70;
if (a < b)
Console.WriteLine("A is less");
else
Console.WriteLine("B is less");
Console.ReadKey();
}
Nesting If Statements:-
When we use multiple if statements, means that if within if its called nesting
if.
Syntax:- if(condition)
{
if(condition)
{
//statements;
}
}
E.g:- static void main(string[] args)
{
int a = 50, b = 70;
if (a < b)
Console.WriteLine("A is less");
else if (a > b)
Console.WriteLine("B is less");
else if (a == b)
Console.WriteLine("Both are same");
Console.ReadKey();
}
If..else Ladder:-
There is another way of putting if is together when multipath decisions are
involved. A multipath decision is a chain of if, in which the statement associated
with each else is an if.
Syntax:- if(condition)
//statements;
else if(condition)
//statements;
else if(condition)
//statements;
statements;
36
2). Switch Statement:-
We have seen that when one of many alternatives has to be selected, we can
design a program using if statements to control the selection. However, the
complexity of such a program increases dramatically, when the alternatives
increase. The program becomes difficult to read and follow. At times, it may
confuse even the designer of the program. Fortunately, C# has a built in multiway
decision statement known as a switch. The switch statement tests the value of a
given variable against a list of case values and when a match is found, a block of
statements associated with that case is executable.
37
break;
}
Console.ReadLine();
}
}
}
38
Console.ReadLine();
}
}
}
39
E.g:-
namespace template_class
{
class for_loop
{
static void Main(string[] args)
{
int i ,n;
Console.Write("Enter n:-");
n = int.Parse(Console.ReadLine());
for (i = 1; i <= n; i++)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
Nesting For loop:-
Syntax:-
For(initialization; condition; increment)
{
for(initialization; condition; increment)
{
statements;
}
statements;
}
40
public static void Main()
{
int [] arr = {10,20,30,40,50};
foreach(int i in arr)
{
Console.WriteLine(i);
}
}
}
Jumping Statement:-
Loops perform a set of operations repeatedly until the control variable fails to
satisfy the test condition. The number of times a loop is repeated is decided in
advance and the test condition is written to achieve this. Sometimes, when
executing a loop it becomes desirable to skip a part of the loop or to leave the loop
as soon as a certain condition occurs. C# permits a jump from one statement to the
end or beginning of a loop as well as jump out of a loop. The jumping statements
are;
1). Break Statement:-
An early exit from a loop can be accomplished by using the break statement. We
have already seen the use of break in the switch statement. This statement can
also be used in while, do..while or for loops for an early exit.
2). Continue Statement:-
During the loop operation, it may be necessary to skip a part of the body of the
loop under certain condition. Like the break statement, C# supports another similar
statement called the continue statement. However, unlike break which causes the
loop to be terminated, the continue statement, as the name implies, causes the
loop to continue with the next iteration after skipping any statements in between.
The continue statement tell the compiler. “Skip the following statements and
continue with the next iteration”.
3). Goto Statement:- (Labelled Jump)
As we have seen that the break will enable us to come out of only the nearest
loop and the continue will enable us to restart the current loop. If we want to jump
a set of nested loops or to continue a loop that is outside the current one, we may
have to use the concept labeling and the goto statement. C# has retained the
infamous goto and also permits us to use label. A label is any valid C# variable
name ending with a colon. We can use labels anywhere in a program and use the
goto statement to transfer the control to the statement marked by the label.
Array:-
An array is a group of contiguous or related data items that share a common
name. For instance, we can define an array name marks to represent a set of
marks of a class of students. A particular value is indicated by writing a number
called index number or subscript in brackets.
Creating an Array:-
Like other variables, arrays must be declared and created in the computer
memory before they are used. Creation of an array involves three steps;
41
1). Declaring an array:-
Arrays in C# are declared as follows;
Type[] arrayname;
E.g:- int[] marks;
Types of Array:-
An array can be of the following types;
1). One Dimensional Array:-
An array having only one subscript /dimension is called single or one
dimensional array.
E.g:- int[] a=new int[5];
namespace template_class
{
class one_array
{
static void Main(string[] args)
{
int[] a = new int[10];
int i;
42
for (i = 0; i < 10; i++)
{
Console.Write("Enter value of an array:-");
a[i]= int.Parse(Console.ReadLine());
}
Console.WriteLine("Result is :-");
for (i = 0; i < 10; i++)
{
Console.Write(a[i]);
}
Console.ReadKey();
}
}
}
2). Multidimensional Array:-
An array having more than one dimension is called a multi dimensional or
rectangular or two dimensional array.
E.g:- int[,]a=new int[2,2];
namespace template_class
{
class two_array
{
static void Main(string[] args)
{
int[,] a = new int[2, 2];
int[,] b = new int[2, 2];
int[,] t = new int[2, 2];
int i, j;
43
Console.WriteLine(" ");
}
Console.ReadKey();
}
}
}
3). Jagged Array:-
A jagged array is an array whose elements are also arrays. The elements of
a jagged array can be of different dimensions and sizes. In other words, we can call
a jagged array as an array of arrays or we can say that it’s a variable sized
array.
E.g:-
namespace template_class
{
class jagged_array
{
static void Main(string[] args)
{
int[][] student=new int[4][];
student[0]=new int[4];
student[1]=new int[2];
student[2]=new int[1];
student[3]=new int[3];
//first row
student[0][0] = 65;
student[0][1] = 55;
student[0][2] = 78;
student[0][3] = 88;
//second row
student[1][0] = 62;
student[1][1] = 87;
//third row
student[2][0] = 83;
//fourth row
student[3][0] = 54;
student[3][1] = 74;
student[3][2] = 65;
Console.WriteLine("Result is:-");
for (int i = 0; i < student.Length; i++)
{
//returns the no. of elements in each row and this varies row from row
for (int j = 0; j < student[i].Length; j++) {
Console.Write(student[i][j]);
}
Console.WriteLine(" ");
}
44
Console.ReadKey();
}
}
}
Array with Foreach Loop:-
E.g:-
namespace template_class
{
class foreach_array
{
static void Main(string[] args)
{
int[] a = new int[10];
int i;
for (i = 0; i < 10; i++)
{
Console.Write("Enter an array:-");
a[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("The result is:-");
foreach (int j in a)
{
i = j;
Console.WriteLine(j);
}
Console.ReadKey();
}
}
}
Param Array:-
At times, while declaring method, we are not sure of the arguments passes as a
parameter. C# param arrays or parameter arrays come into help at these times.
E.g:-
Namespace paramarray
{
class array_param
{
public int addele(params int[] a)
{
int s=0;
foreach(int i in a)
{
s+=i;
}
return s;
}
}
class Test
{
static void Main(string[] args)
{
45
array_param ap=new array_param();
int s=ap.addele(11,12,13,14,15);
Console.WriteLine(“The sum is :-“+s);
Console.ReadKey();
}
}
}
Name Description
IsFixedSize Gets a value indicating whether the Array has a fixed size.
46
GetValue Gets the value at the specified position in the one
dimensional Array.
IndexOf Searches for the specified object and returns the index
of the first occurrence within the entire one dimensional
array.
Reverse Reverses the sequence of the elements in the entire one
dimensional Array.
SetValue Sets a value to the elements at the specified position in
the one-dimensional Array.
Sort Sorts the elements in an entire one-dimensional Array.
ArrayList Class:-
System.Collection namespaces defines a class known as ArrayList that can
store a dynamically sized array of objects. The ArrayList class includes a number of
methods to support operations such as sorting, removing and enumerating its
contents. It also supports a property a count that gives the number of objects in an
array list and a property Capacity ti modify or read the capacity.
An array list is very similar to an array, except that it has the ability to grow
dynamically. We can create an array list by indicating the initial capacity we want.
E.g:- ArrayList cities= new ArrayList(30);
It creates cities with a capacity to store thirty objects. If we do not specify the
size, it defaults to sizteen. An array list can be really useful if we need to create an
array of objects but we do not know in advance how big the array would be.
Lists some of the most important methods and properties supported by the
ArrayList class.
Methods/Properties Description
47
E.g:-
namespace array_demo
{
class Program
{
static void printarray(int[] arr)
{
Console.WriteLine("\nElements of array is:\n");
foreach (int i in arr)
{
Console.Write("\t{0}", i);
}
Console.WriteLine("\n");
}
static void Main(string[] args)
{
//Initializing and storing value in arr1
int[] arr1 = new int[5] { 43, 25, 33, 14, 5 };
int[] arr2 = new int[5];
int len, rank;
bool fixedsize, read_only;
//Sorting an array
Array.Sort(arr1);
printarray(arr1);
48
//Removing items from array.
Array.Clear(arr1, 0, 5);
printarray(arr1);
Console.ReadLine();
}
}
}
Array as an Argument:-
An array can also be passed to method as argument or parameter. A method
process the array and returns output. Passing array as parameter in C# is pretty
easy as passing other values as parameter. Just create a function that accepts
array as argument and then process them.
E.g:-
namespace array_demo
{
class parameter
{
static void printarray(int[] newarray)
{
int i,sum=0;
Console.Write("\n\nYou entered:\t");
for (i = 0; i < 4; i++)
{
Console.Write("{0}\t", newarray[i]);
sum = sum + newarray[i];
}
Console.Write("\n\nAnd sum of all value is:\t{0}", sum);
Console.ReadLine();
}
static void Main(string[] args)
{
int[] arr = new int[4];
int i;
for (i = 0; i < 4; i++)
{
Console.Write("Enter number:\t");
arr[i] = Convert.ToInt32(Console.ReadLine());
}
// passing array as argument
parameter.printarray(arr);
}
}
}
In the above example, we create an array and accept some integer values
from the user at a runtime. Then we passes array as argument to printarray(int[]
newarray) for printing and other calculation. It is same as other value passed as a
parameter to the function.
49
BitArray Class:-
The BitArray class allows us to deal with the values in their binary
representation. Data that we add to such collections gets stored in these
collections- represented in their binary form, with each element signifying a bit’s
value(with the value false representing 0 and true representing 1).
Properties of the BitArray class:-
Name Description
String:-
In C#, we can use strings as array of characters, however, more common
practice is to use the String keyword to declare a string variable. The string
keyword is an alias for the System.String class.
We can create string object using one of the following methods:
1). Assigning string literals
2). Copying from one object to another
3). Concatenating two objects
4). Reading from the keyboard
5). Using ToString method
50
Each above points described in below;
Chars Gets the char object at a specified position in the current string
object
Length Gets the number of characters in the current string object
51
Methods of String class:-
The string objects are immutable, meaning that we cannot modify the
characters contained in them. However, since the string is an alias for the
predefined System.String class in the common Language Runtime (CLR), there are
many built in operations available that work with strings.
The string class has numerous methods that help us in working with the string
objects. The following table provides some of the most commonly used methods:
Name Description
52
E.g:- 1). Compare two strings.
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str1 = "National";
string str2 = "College";
if (String.Compare(str1, str2) == 0)
{
Console.WriteLine(str1 + " and " + str2 + " are equal.");
}
else
{
Console.WriteLine(str1 + " and " + str2 + " are not equal.");
}
Console.ReadKey() ;
}
}
}
o/p:- National and College are not equal
53
3). Substring a string:-
namespace StringDemo
{
Class program
{
static void Main(String[] args)
{
string s=”National Computer College”;
Console.WriteLine(s);
String s1=s.Substring(18);
Console.WriteLine(s1);
}
Console.ReadKey();
}
}
54