CS2014 C# Unit 1
CS2014 C# Unit 1
com
UNIT-I
INTRODUCTION TO C#
Introducing C#,
Since its original 1.0 release, C# has been evolving at a rapid pace. Not long after
C# 1.0,Microsoft released version 1.1. It contained many minor tweaks but added
no major features. However, the situation was much different with the release of
C# 2.0. C# 2.0 was a watershed event in the lifecycle of C# because it added many
new features, such as generics, partial types, and anonymous methods, that
fundamentally expanded the scope, power, and range of the language. Version 2.0
firmly put C# at the forefront of computer language development. It also
demonstrated Microsoft’s long-term commitment to the language.
The next major release of C# was 3.0, and this is the version of C# described by
this book.Because of the many new features added by C# 2.0, one might have
expected the development of C# to slow a bit, just to let programmers catch up, but
this was not the case. With the release of C# 3.0, Microsoft once again put C# on
the cutting edge of language design, this time dding a set of innovative features
that redefined the programming landscape. Here is list of what 3.0 has added to
the language:
• Anonymous types
• Auto-implemented properties
• Extension methods
• Implicitly typed variables
• Lambda expressions
• Language-integrated query (LINQ)
• Object and collection initializers
www.Vidyarthiplus.com
www.Vidyarthiplus.com
• Partial methods
Although all of these features are important and have significant impact on the
language, the two that are the most exciting are language-integrated query (LINQ)
and lambda expressions. LINQ enables you to write database-style queries using
C# programming elements. However, the LINQ syntax is not limited to only
databases. It can also be used with arrays and collections. Thus, LINQ offers a new
way to approach several common programming tasks. Lambda expressions are
often used in LINQ expressions, but can also be used elsewhere. They implement a
functional-style syntax that uses the lambda operator =>. Together, LINQ and
lambda expressions add an entirely new dimension to C# programming.
Throughout the course of this book, you will see how these features are
revolutionizing the way that C# code is written.
Although C# is a computer language that can be studied on its own, it has a special
relationship to its runtime environment, the .NET Framework. The reason for this
is twofold. First, C# was initially designed by Microsoft to create code for the
.NET Framework. Second, the libraries used by C# are the ones defined by the
.NET Framework. Thus, even though it is theoretically possible to separate C# the
language from the .NET environment, in practice the two are closely linked.
Because of this, it is important to have ageneral understanding of the .NET
Framework and why it is important to C#.
Understanding .NET
www.Vidyarthiplus.com
www.Vidyarthiplus.com
The .NET Framework defines an environment that supports the development and
execution of highly distributed, component-based applications. It enables differing
computer languages to work together and provides for security, program
portability, and a common programming model for the Windows platform. As it
relates to C#, the .NET Framework defines two very important entities. The first is
the Common Language Runtime (CLR). This is the system that manages the
execution of your program. Along with other benefits, the Common Language
Runtime is the part of the .NET Framework that enables programs to be portable,
supports mixed-language programming, and provides for secure execution.
The second entity is the .NET class library. This library gives your program access
to the runtime environment. For example, if you want to perform I/O, such as
displaying something on the screen, you will use the .NET class library to do it. If
you are new to programming, then the term class may be new. Although it is
explained in detail later in this book, for now a brief definition will suffice: a class
is an object-oriented construct that helps organize programs. As long as your
program restricts itself to the features defined by the .NET class library, your
programs can run anywhere that the .NET runtime system is supported. Since C#
automatically uses the .NET Framework class library, C# programs are
utomatically portable to all .NET environments.
Basics
Identifier
An identifier is the name of an element in the code There are certain standard
naming conventions to follow when selecting names for elements.
An identifier can:
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Form feed \f
Backslash \\
Single quote \'
Double quote \"
Line feed \n
Variables
Variables are identifiers associated with values. They are declared by writing
the variable's type and name, and are optionally initialized in the same
statement by assigning a value.
Declare
int MyInt; // Declaring an uninitialized variable called 'MyInt', of type 'int'
Initialize
int MyInt; // Declaring an uninitialized variable
MyInt = 35; // Initializing the variable
Declare & initialize
int MyInt = 35; // Declaring and initializing the variable at the same time
Multiple variables of the same type can be declared and initialized in one
statement.
int a, b; // Declaring multiple variable of the same type
DATATYPES
www.Vidyarthiplus.com
www.Vidyarthiplus.com
C# contains two general categories of built-in data types: value types and reference
types. The difference between the two types is what a variable contains. For a
value type, a variable holds an actual value, such 3.1416 or 212. For a reference
type, a variable holds a reference to the value. The most commonly used reference
type is the class, and a discussion of classes and reference types is deferred until
later in this book. The value types are described here. At the core of C# are the 13
value types shown in Table 3-1. Collectively, these are referred to as the simple
types. They are called simple types because they consist of a singlevalue. (In other
words, they are not a composite of two or more values.) They form thefoundation
of C#’s type system, providing the basic, low-level data elements upon whicha
program operates. The simple types are also sometimes referred to as primitive
types.
Type Meaning
bool Represents true/false values
byte 8-bit unsigned integer
char Character
decimal Numeric type for financial
calculations
double Double-precision floating point
float Single-precision floating point
int Integer
long Long integer
sbyte 8-bit signed integer
short Short integer
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Integers
C# defines nine integer types: char, byte, sbyte, short, ushort, int, uint, long, and
ulong.However, the char type is primarily used for representing characters, and it
is discussed later in this chapter. The remaining eight integer types are used for
numeric calculations.Their bit-width and ranges are shown here:
As the table shows, C# defines both signed and unsigned versions of the various
integer types. The difference between signed and unsigned integers is in the way
the high-order bit of the integer is interpreted. If a signed integer is specified, then
the C# compiler will generate code that assumes the high-order bit of an integer is
to be used as a sign flag. If the sign flag is 0, then the number is positive; if it is 1,
www.Vidyarthiplus.com
www.Vidyarthiplus.com
then the number is negative. Negative numbers are almost always represented
using the two’s complement approach. In this method, all bits in the negative
number are reversed, and then 1 is added to this number.Signed integers are
important for a great many algorithms, but they have only half the absolute
magnitude of their unsigned relatives. For example, as a short, here is 32,767:
0111111111111111
For a signed value, if the high-order bit were set to 1, the number would then be
interpreted as –1 (assuming the two’s complement format). However, if you
declared this to be a ushort, then when the high-order bit was set to 1, the number
would become 65,535. Probably the most commonly used integer type is int.
Variables of type int are often employed to control loops, to index arrays, and for
general-purpose integer math. When you need an integer that has a range greater
than int, you have many options. If the value you want to store is unsigned, you
can use uint. For large signed values, use long. For large unsigned values, use
ulong. For example, here is a program that computes the distance from the Earth to
the sun, in inches. Because this value is so large, the program uses a long variable
to hold it.
// Compute the distance from the Earth to the sun, in inches.
using System;
class Inches {
static void Main() {
long inches;
long miles;
miles = 93000000; // 93,000,000 miles to the sun
// 5,280 feet in a mile, 12 inches in a foot.
inches = miles * 5280 * 12;
Console.WriteLine("Distance to the sun: " +
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Floating-Point Types
The floating-point types can represent numbers that have fractional components.
There are two kinds of floating-point types, float and double, which represent
single- and doubleprecision numbers, respectively. The type float is 32 bits wide
and has an approximate range of 1.5E–45 to 3.4E+38. The double type is 64 bits
wide and has an approximate range of 5E–324 to 1.7E+308. Of the two, double is
the most commonly used. One reason for this is that many of the math functions in
C#’s class library (which is the .NET Framework library) use double
values. For example, the Sqrt( ) method (which is defined by the library class
System.Math)returns a double value that is the square root of its double
argument. Here, Sqrt( ) is used to compute the radius of a circle given the circle’s
area:
www.Vidyarthiplus.com
www.Vidyarthiplus.com
r = Math.Sqrt(area / 3.1416);
Console.WriteLine("Radius is " + r);
}
}
Radius is 1.78412203012729
One other point about the preceding example. As mentioned, Sqrt( ) is a member
of the Math class. Notice how Sqrt( ) is called; it is preceded by the name Math.
This is similar to the way Console precedes WriteLine( ). Although not all
standard methods are called by specifying their class name first, several are, as the
next example shows.The following program demonstrates several of C#’s
trigonometric functions, which are also part of C#’s math library. They also
operate on double data. The program displays the sine, cosine, and tangent for the
angles (measured in radians) from 0.1 to 1.0.
Characters
In C#, characters are not 8-bit quantities like they are in many other computer
languages,such as C++. Instead, C# uses a 16-bit character type called Unicode.
Unicode defines a character set that is large enough to represent all of the
characters found in all human languages. Although many languages, such as
English, French, or German, use relatively small alphabets, some languages, such
as Chinese, use very large character sets that cannot be represented using just 8
bits. To address this situation, in C#, char is an unsigned 16-bit type having a
range of 0 to 65,535. The standard 8-bit ASCII character set is a subset of
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Unicode and ranges from 0 to 127. Thus, the ASCII characters are still valid C#
characters.A character variable can be assigned a value by enclosing the character
inside singlequotes. For example, this assigns X to the variable ch:
char ch;
ch = 'X';
You can output a char value using a WriteLine( ) statement. For example, this
line outputs the value in ch:
char ch;
ch = 88; // error, won't work
The reason the preceding code will not work is that 10 is an integer value, and it
won’t automatically convert to a char. If you attempt to compile this code, you
will see an error message. To make the assignment legal, you would need to
employ a cast, which is described later in this chapter.
The bool type represents true/false values. C# defines the values true and false
using the reserved words true and false. Thus, a variable or expression of type
www.Vidyarthiplus.com
www.Vidyarthiplus.com
bool will be one of these two values. Furthermore, there is no conversion defined
between bool and integer values. For example, 1 does not convert to true, and 0
does not convert to false.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
10 > 9 is True
There are three interesting things to notice about this program. First, as you can
see,when a bool value is output by WriteLine( ), ―True‖ or ―False‖ is displayed.
Second, the value of a bool variable is sufficient, by itself, to control the if
statement. There is no need to write an if statement like this:
if(b == true) ...
Third, the outcome of a relational operator, such as <, is a bool value. This is why
the expression 10 > 9 displays the value ―True.‖ Further, the extra set of
parentheses around 10 > 9 is necessary because the + operator has a higher
precedence than the >.
Operators
Operator category Operators
Arithmetic +-*/%
Logical (boolean and bitwise) & | ^ ! ~ && ||
String concatenation +
Increment, decrement ++ --
Shift << >>
Relational == != < > <= >=
Assignment = += -= *= /= %= &= |= ^= <<= >>=
Member access .
Indexing []
Cast ()
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Conditional ? :
Delegate concatenation and removal + -
Object creation new
Type information as is sizeof typeof
Overflow exception control checked unchecked
Indirection and Address * -> [] &
Operator overloading
Some of the existing operators can be overloaded by writing an overload method.
public static Foo operator+(Foo foo, Bar bar)
{
return new Foo(foo.Value + bar.Value);
}
These are the overloadable operators:
Operators
+ - ! ~ ++ -- true false Unary operators
+ - * / % & | ^ << >> Binary operators
Comparison operators, must be overloaded in
== != < > <= >=
pairs
Assignment operators (+=, *= etc.) are combinations of a binary operator
and the assignment operator (=) and will be evaluated using the ordinary
operators, which can be overloaded.
Cast operators (( )) cannot be overloaded, but you can define conversion
operators.
Array indexing ([ ]) operator is not overloadable, but you can define new
indexers.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Conversion operators
The cast operator is not overloadable but you can write a conversion operator
method which lives in the target class. Conversion methods can define two
varieties of operators, implicit and explicit conversion operators. The implicit
operator will cast without specifying with the cast operator (( )) and the explicit
operator requires it to be used.
Implicit conversion operator
class Foo
{
public int Value;
public static implicit operator Foo(int value)
{
return new Foo(value)
}
}
//Implicit conversion
Foo foo = 2;
Explicit conversion operator
class Foo
{
public int Value;
public static explicit operator Foo(int value)
{
return new Foo(value)
}
}
//Explicit conversion
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Expressions
www.Vidyarthiplus.com
www.Vidyarthiplus.com
// A promotion surprise!
using System;
class PromDemo {
www.Vidyarthiplus.com
www.Vidyarthiplus.com
The if Statement
if(condition) statement;
else statement;
www.Vidyarthiplus.com
www.Vidyarthiplus.com
where the targets of the if and else are single statements. The else clause is
optional. The targets of both the if and else can be blocks of statements. The
general form of the if using blocks of statements is
if(condition)
{
statement sequence
}
else
{
statement sequence
}
If the conditional expression is true, the target of the if will be executed; otherwise,
if it exists, the target of the else will be executed. At no time will both of them be
executed. The conditional expression controlling the if must produce a bool result.
Here is a simple example that uses an if and else to report if a number is positive or
negative:
www.Vidyarthiplus.com
www.Vidyarthiplus.com
else Console.WriteLine("positive");
}
}
}
The output is shown here:
Testing -5: negative
Testing -4: negative
Testing -3: negative
Testing -2: negative
Testing -1: negative
Testing 0: positive
Testing 1: positive
Testing 2: positive
Testing 3: positive
Testing 4: positive
Testing 5: positive
In this example, if i is less than zero, then the target of the if is executed.
Otherwise, the target of the else is executed. In no case are both executed.
Nested ifs A nested if is an if statement that is the target of another if or else.
Nested ifs are very common in programming. The main thing to remember about
nested ifs in C# is that an else clause always refers to the nearest if statement that is
within the same block as the else and not already associated with an else. Here is
an example:
if(i == 10) {
if(j < 20) a = b;
www.Vidyarthiplus.com
www.Vidyarthiplus.com
As the comments indicate, the final else is not associated with if(j < 20) because it
is not in the same block (even though it is the nearest if without an else). Rather,
the final else is associated with if(i == 10). The inner else refers to if(k > 100)
because it is the closest if within the same block.
The following program demonstrates a nested if. In the positive/negative program
shown earlier, zero is reported as positive. However, as a general rule, zero is
considered signless. The following version of the program reports zero as being
neither positive nor negative.
www.Vidyarthiplus.com
www.Vidyarthiplus.com
The goto
www.Vidyarthiplus.com
www.Vidyarthiplus.com
The goto requires a label for operation. A label is a valid C# identifier followed by
a colon. The label must be in the same method as the goto that uses it and within
scope. For
example, a loop from 1 to 100 could be written using a goto and a label, as shown
here:
x = 1;
loop1:
x++;
if(x < 100) goto loop1;
The goto can also be used to jump to a case or default statement within a switch.
Technically, the case and default statements of a switch are labels. Thus, they can
be targets of a goto. However, the goto statement must be executed from within
the switch. That is, you cannot use the goto to jump into a switch statement. Here
is an example that illustrates
goto with a switch:
www.Vidyarthiplus.com
www.Vidyarthiplus.com
goto case 1;
case 3:
Console.WriteLine("In case 3");
goto default;
default:
Console.WriteLine("In default");
break;
}
Console.WriteLine();
}
// goto case 1; // Error! Can't jump into a switch.
}
}
The output from the program is shown here:
In case 1
In case 3
In default
In case 2
In case 1
In case 3
In default
In case 3
In default
In default
www.Vidyarthiplus.com
www.Vidyarthiplus.com
One-Dimensional Arrays
A one-dimensional array is a list of related variables. Such lists are common in
programming.
For example, you might use a one-dimensional array to store the account numbers
of the
active users on a network. Another array might store the current batting averages
for a
baseball team.
Because arrays in C# are implemented as objects, two steps are needed to obtain an
array for use in your program. First, you must declare a variable that can refer to an
array.
Second, you must create an instance of the array by use of new. Therefore, to
declare a onedimensional
array, you will typically use this general form:
type[ ] array-name = new type[size];
Here, type declares the element type of the array. The element type determines the
data type
of each element that comprises the array. Notice the square brackets that follow
type. They
indicate that a one-dimensional array is being declared. The number of elements
that the
array will hold is determined by size.
// Demonstrate a one-dimensional array.
using System;
class ArrayDemo {
static void Main() {
int[] sample = new int[10];
www.Vidyarthiplus.com
www.Vidyarthiplus.com
int i;
for(i = 0; i < 10; i = i+1)
sample[i] = i;
for(i = 0; i < 10; i = i+1)
Console.WriteLine("sample[" + i + "]: " + sample[i]);
}
}
The output from the program is shown here:
sample[0]: 0
sample[1]: 1
sample[2]: 2
sample[3]: 3
sample[4]: 4
sample[5]: 5
sample[6]: 6
sample[7]: 7
sample[8]: 8
sample[9]: 9
Strings
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Chapter 2, but you did not know it.When you create a string literal, you are
actually creating a string object. For example, in thestatement
Console.WriteLine("In C#, strings are objects.");the string ―In C#, strings are
objects.‖ is automatically made into a string object by C#. Thus,the use of the
string class has been ―below the surface‖ in the preceding programs. In this
section, you will learn to handle them explicitly.
Constructing Strings
The easiest way to construct a string is to use a string literal. For example, here str
is a string reference variable that is assigned a reference to a string literal:
string str = "C# strings are powerful."; In this case, str is initialized to the character
sequence ―C# strings are powerful.‖You can also create a string from a char array.
For example:
char[] charray = {'t', 'e', 's', 't'};
string str = new string(charray);
Once you have created a string object, you can use it nearly anywhere that a
quoted string is allowed. For example, you can use a string object as an argument
to WriteLine( ),as shown in this example:
// Introduce string.
using System;
class StringDemo {
static void Main() {
www.Vidyarthiplus.com
www.Vidyarthiplus.com
char[] charray = {'A', ' ', 's', 't', 'r', 'i', 'n', 'g', '.' };
string str1 = new string(charray);
string str2 = "Another string.";
Console.WriteLine(str1);
Console.WriteLine(str2);
}
}
Operating on Strings
The string class contains several methods that operate on strings. Table 7-1 shows
a few. The string type also includes the Length property, which contains the
length of the string.To obtain the value of an individual character of a string, you
simply use an index.
For example:
string str = "test";
Console.WriteLine(str[0]);
STRUCTURE
A structure is similar to aclass, but is a value type, rather than a reference type.
Structures are declared using the keyword struct and are syntactically similar to
classes.Here is the general form of a struct:
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com
struct Book {
public string Author;
public string Title;
public int Copyright;
public Book(string a, string t, int c) {
Author = a;
Title = t;
Copyright = c;
}
}
// Demonstrate Book structure.
class StructDemo {
static void Main() {
Book book1 = new Book("Herb Schildt",
"C# 3.0: The Complete Reference",
2009); // explicit constructor
Book book2 = new Book(); // default constructor
Book book3; // no constructor
Console.WriteLine(book1.Title + " by " + book1.Author +
", (c) " + book1.Copyright);
Console.WriteLine();
if(book2.Title == null)
Console.WriteLine("book2.Title is null.");
// Now, give book2 some info.
book2.Title = "Brave New World";
book2.Author = "Aldous Huxley";
book2.Copyright = 1932;
www.Vidyarthiplus.com
www.Vidyarthiplus.com
Enumerations
www.Vidyarthiplus.com
www.Vidyarthiplus.com
A key point to understand about an enumeration is that each of the symbols stands
for an integer value. However, no implicit conversions are defined between an
enum type and the built-in integer types, so an explicit cast must be used. Also, a
cast is required when converting between two enumeration types. Since
enumerations represent integer values, you can use an enumeration to control a
switch statement or as the control variable in a for loop, for example.
Each enumeration symbol is given a value one greater than the symbol that
precedes it. By default, the value of the first enumeration symbol is 0. Therefore, in
the Apple enumeration, Jonathan is 0, GoldenDel is 1, RedDel is 2, and so on.
The members of an enumeration are accessed through their type name via the dot
operator. For example
// Demonstrate an enumeration.
using System;
class EnumDemo {
enum Apple { Jonathan, GoldenDel, RedDel, Winesap,
Cortland, McIntosh };
static void Main() {
www.Vidyarthiplus.com
www.Vidyarthiplus.com
string[] color = {
"Red",
"Yellow",
"Red",
"Red",
"Red",
"Reddish Green"
};
Apple i; // declare an enum variable
// Use i to cycle through the enum.
for(i = Apple.Jonathan; i <= Apple.McIntosh; i++)
Console.WriteLine(i + " has value of " + (int)i);
Console.WriteLine();
// Use an enumeration to index an array.
for(i = Apple.Jonathan; i <= Apple.McIntosh; i++)
Console.WriteLine("Color of " + i + " is " +
color[(int)i]);
}
}
The output from the program is shown here:
Jonathan has value of 0
GoldenDel has value of 1
RedDel has value of 2
Winesap has value of 3
Cortland has value of 4
McIntosh has value of 5
Color of Jonathan is Red
www.Vidyarthiplus.com
www.Vidyarthiplus.com
www.Vidyarthiplus.com