0% found this document useful (0 votes)
25 views

CS2014 C# Unit 1

CS2014 C# Unit 1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

CS2014 C# Unit 1

CS2014 C# Unit 1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

www.Vidyarthiplus.

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.

How C# Relates to the .NET Framework

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

start with a "_".


contain both upper case and lower case Unicode letters. Case is significant.
An identifier cannot:
start with a numeral.
start with a symbol, unless it is a keyword (check Keywords).
have more than 511 chars
Literals
Integers
octal 0365, 0[0..7]*
hexadecimal 0xF5, 0x[0..9, A..F, a..f]*
decimal 245, [1..9][0..9]*
Floating-point values
float 23.5F, 23.5f; 1.72E3F, 1.72E3f, 1.72e3F, 1.72e3f
double 23.5, 23.5D, 23.5d; 1.72E3, 1.72E3D, ...
Character literals
char 'a', 'Z', '\u0231'
String literals
"Hello,world"
String
"C:\\Windows\\", @"C:\Windows\"
Characters escapes in strings
Unicode character \u followed by the hexadecimal unicode code point
Tab \t
Backspace \b
Carriage return \r

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

int a = 2, b = 3; // Declaring and initializing multiple variables of the same type

DATATYPES

www.Vidyarthiplus.com
www.Vidyarthiplus.com

C#’s Value Types

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

uint An unsigned integer


ulong An unsigned long integer
ushort An unsigned short integer

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:

Type Width in Bits Range


byte 8 0 to 255
sbyte 8 –128 to 127
short 16 –32,768 to 32,767
ushort 16 0 to 65,535
int 32 –2,147,483,648 to 2,147,483,647
uint 32 0 to 4,294,967,295
long 64 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
ulong 64 0 to 18,446,744,073,709,551,615

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

inches + " inches.");


}
}
Here is the output from the program:
Distance to the sun: 5892480000000 inches.
Clearly, the result could not have been held in an int or uint variable.
The smallest integer types are byte and sbyte. The byte type is an unsigned value
between 0 and 255. Variables of type byte are especially useful when working
with raw
binary data, such as a byte stream produced by some device. For small signed
integers,
use sbyte. Here is an example that uses a variable of type byte to control a for loop
that
produces the summation of the number 100:
// Use byte.
using System;
class Use_byte {
static void Main() {
byte x;
int sum;
sum = 0;
for(x = 1; x <= 100; x++)
sum = sum + x;
Console.WriteLine("Summation of 100 is " + sum);
}
}
The output from the program is shown here:

www.Vidyarthiplus.com
www.Vidyarthiplus.com

Summation of 100 is 5050


Since the for loop runs only from 0 to 100, which is well within the range of a
byte, there is no need to use a larger type variable to control it.When you need an
integer that is larger than a byte or sbyte, but smaller than an int or uint, use short
or ushort.

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:

// Find the radius of a circle given its area.


using System;
class FindRadius {
static void Main() {
Double r;
Double area;
area = 10.0;

www.Vidyarthiplus.com
www.Vidyarthiplus.com

r = Math.Sqrt(area / 3.1416);
Console.WriteLine("Radius is " + r);
}
}

The output from the program is shown here:

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:

Console.WriteLine("This is ch: " + ch);

Although char is defined by C# as an integer type, it cannot be freely mixed with


integers in all cases. This is because there are no automatic type conversions from
integer to char. For example, the following fragment is invalid:

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

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.

Here is a program that demonstrates the bool type:


// Demonstrate bool values.
using System;
class BoolDemo {
static void Main() {
bool b;
b = false;
Console.WriteLine("b is " + b);
b = true;
Console.WriteLine("b is " + b);
// A bool value can control the if statement.
if(b) Console.WriteLine("This is executed.");
b = false;
if(b) Console.WriteLine("This is not executed.");
// Outcome of a relational operator is a bool value.
Console.WriteLine("10 > 9 is " + (10 > 9));
}
}

The output generated by this program is shown here:


b is False
b is True
This is executed.

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

Foo foo = (Foo)2;


as operator
The as operator will attempt to do a silent cast to a given type. If it succeeds it will
return the object as the new type, if it fails it will return a null reference.
Stream stream = File.Open(@"C:\Temp\data.dat");
FileStream fstream = stream as FileStream; //Will return an object.

String str = stream as String; //Will fail and return null.

Expressions

Type Conversion in Expressions


In addition to occurring within an assignment, type conversions also take place
within an expression. In an expression, you can freely mix two or more different
types of data as long as they are compatible with each other. For example, you can
mix short and long within an expression because they are both numeric types.
When different types of data are mixed within an expression, they are converted to
the same type, on an operation-by-operation basis.The conversions are
accomplished through the use of C#’s type promotion rules. Here is
the algorithm that they define for binary operations:

IF one operand is a decimal, THEN the other operand is promoted to decimal


(unless it is of type fl oat or double, in which case an error results).
ELSE IF one operand is a double, the second is promoted to double.
ELSE IF one operand is a fl oat, the second is promoted to fl oat.
ELSE IF one operand is a ulong, the second is promoted to ulong (unless it is
of type sbyte, short, int, or long, in which case an error results).

www.Vidyarthiplus.com
www.Vidyarthiplus.com

ELSE IF one operand is a long, the second is promoted to long.


ELSE IF one operand is a uint and the second is of type sbyte, short, or int,
both are promoted to long.
ELSE IF one operand is a uint, the second is promoted to uint.
ELSE both operands are promoted to int.
There are a couple of important points to be made about the type promotion rules.
First, not all types can be mixed in an expression. Specifically, there is no implicit
conversion from float or double to decimal, and it is not possible to mix ulong
with any signed integer type. To mix these types requires the use of an explicit
cast. Second, pay special attention to the last rule. It states that if none of the
preceding rules applies, then all other operands are promoted to int. Therefore, in
an expression, all char, sbyte, byte, ushort, and short values are promoted to int
for the purposes of calculation.This is called integer promotion. It also means that
the outcome of all arithmetic operations will be no smaller than int.It is important
to understand that type promotions only apply to the values operated upon when an
expression is evaluated. For example, if the value of a byte variable ispromoted to
int inside an expression, outside the expression, the variable is still a byte.
Type promotion only affects the evaluation of an expression.Type promotion can,
however, lead to somewhat unexpected results. For example, when an arithmetic
operation involves two byte values, the following sequence occurs. First, the
byte operands are promoted to int. Then the operation takes place, yielding an int
result.Thus, the outcome of an operation involving two byte values will be an int.
This is not what you might intuitively expect. Consider the following program

// A promotion surprise!
using System;
class PromDemo {

www.Vidyarthiplus.com
www.Vidyarthiplus.com

static void Main() {


byte b;
b = 10;
b = (byte) (b * b); // cast needed!!
Console.WriteLine("b: "+ b);
}
}
BRANCHING

There are three categories of program control statements: selection statements,


which are the if and the switch;iteration statements, which consist of the for,
while, do-while, and foreach loops; and jump statements, which include break,
continue, goto, return, and throw. Except for throw,which is part of C#’s
exception-handling mechanism

The if Statement

Chapter 2 introduced the if statement. It is examined in detail here. The complete


form of the if statement is

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:

// Determine if a value is positive or negative.


using System;
class PosNeg {
static void Main() {
int i;
for(i=-5; i <= 5; i++) {
Console.Write("Testing " + i + ": ");
if(i < 0) Console.WriteLine("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

if(k > 100) c = d;


else a = c; // this else refers to if(k > 100)
}
else a = d; // this else refers to if(i == 10)

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.

// Determine if a value is positive, negative, or zero.


using System;
class PosNegZero {
static void Main() {
int i;
for(i=-5; i <= 5; i++) {
Console.Write("Testing " + i + ": ");
if(i < 0) Console.WriteLine("negative");
else if(i == 0) Console.WriteLine("no sign");
else Console.WriteLine("positive");
}
}
}

www.Vidyarthiplus.com
www.Vidyarthiplus.com

Here is the output:


Testing -5: negative
Testing -4: negative
Testing -3: negative
Testing -2: negative
Testing -1: negative
Testing 0: no sign
Testing 1: positive
Testing 2: positive
Testing 3: positive
Testing 4: positive
Testing 5: positive

The goto

The goto is C#’s unconditional jump statement. When encountered, program


flow jumps to the location specified by the goto. The statement fell out of favor
with programmers many years ago because it encouraged the creation of ―spaghetti
code.‖ However, the goto is still occasionally—and sometimes effectively—used.
This book will not make a judgment regarding its validity as a form of program
control. It should be stated, however, that there are no programming situations that
require the use of the goto statement—it is not necessary for making the language
complete. Rather, goto is a convenience that, if used wisely, can be a benefit in
certain programming situations. As such, the goto is not used in this book outside
of this section. The chief concern most programmers have about the goto is its
tendency to clutter a program and render it nearly unreadable. However, there are
times when the use of the goto can clarify program flow rather than confuse it.

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:

// Use goto with a switch.


using System;
class SwitchGoto {
static void Main() {
for(int i=1; i < 5; i++) {
switch(i) {
case 1:
Console.WriteLine("In case 1");
goto case 3;
case 2:
Console.WriteLine("In case 2");

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

From a day-to-day programming standpoint, one of the most important of C#’s


data types is string. string defines and supports character strings. In many other
programming languages,a string is an array of characters. This is not the case with
C#. In C#, strings are objects. Thus,string is a reference type. Although string is a
built-in data type in C#, a discussion of string needed to wait until classes and
objects had been introduced. Actually, you have been using the string class since

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);
}
}

The output from the program is shown here:


A string.
Another string.

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

struct name : interfaces {


// member declarations
}

The name of the structure is specified by name.Structures cannot inherit other


structures or classes or be used as a base for other structures or classes. (Of course,
like all C# types, structures do inherit object.) However, a structure can implement
one or more interfaces. These are specified after the structure name using a
comma-separated list. Like classes, structure members include methods, fields,
indexers, properties, operator methods, and events. Structures can also define
constructors,but not destructors. However, you cannot define a default
(parameterless) constructor for a structure. The reason for this is that a default
constructor is automatically defined for all structures, and this default constructor
can’t be changed. The default constructor initializes the fields of a structure to their
default value. Since structures do not support inheritance,structure members cannot
be specified as abstract, virtual, or protected.
A structure object can be created using new in the same way as a class
object, but it is not required. When new is used, the specified constructor is called.
When new is not used, the object is still created, but it is not initialized. Thus, you
will need to perform any initialization manually.

Here is an example that uses a structure to hold information about a book:


// Demonstrate a structure.
using System;
// Define a structure.

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

Console.Write("book2 now contains: ");


Console.WriteLine(book2.Title + " by " + book2.Author +
", (c) " + book2.Copyright);
Console.WriteLine();
// Console.WriteLine(book3.Title); // error, must initialize first
book3.Title = "Red Storm Rising";
Console.WriteLine(book3.Title); // now OK
}
}
The output from this program is shown here:
C# 3.0: The Complete Reference by Herb Schildt, (c) 2009
book2.Title is null.
book2 now contains: Brave New World by Aldous Huxley, (c) 1932
Red Storm Rising

Enumerations

An enumeration is a set of named integer constants. The keyword enum declares


an enumerated type. The general form for an enumeration is enum name {
enumeration list };Here, the type name of the enumeration is specified by name.
The enumeration list is a comma-separated list of identifiers.
Here is an example. It defines an enumeration called Apple that enumerates
various types of apples:

enum Apple { Jonathan, GoldenDel, RedDel, Winesap,


Cortland, McIntosh };

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

Console.WriteLine(Apple.RedDel + " has the value " +


(int)Apple.RedDel);
displays
RedDel has the value 2
As the output shows, when an enumerated value is displayed, its name is used. To
obtain
its integer value, a cast to int must be employed.
Here is a program that illustrates the Apple enumeration:

// 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

Color of GoldenDel is Yellow


Color of RedDel is Red
Color of Winesap is Red
Color of Cortland is Red
Color of McIntosh is Reddish Green

www.Vidyarthiplus.com

You might also like