C# Programming
C# Programming
C# Programming
For the .NET Framework version 1.0.3705
Courseware Number #10010B
Contents
Copyright 2002 Third Millennium, LLP, 21 Moon Hill Road, Lexington MA 02421,
USA. All rights reserved.
This product or document is protected by copyright and distributed under license
restricting its use, copying, and distribution. No part of this product or document may be
reproduced in any form by any means without prior written authorization of Third
Millennium, LLP and its licenses, if any.
Microsoft is a registered trademark. Visual C#, Visual Basic, Visual Studio, Windows,
Windows 98, Windows NT, Windows 2000, and Windows XP are either registered
trademarks or trademarks of Microsoft Corporation in the U.S. and/or other countries.
Sun, Sun Microsystems, Java are trademarks or registered trademarks of Sun
Microsystems, Inc. in the United States and other countries.
Other product and company names herein may be the trademark of their respective
owners.
Contents
Table of Contents
C# PROGRAMMING.................................................................................................................................................. 1
TABLE OF CONTENTS...................................................................................................................................................3
STUDENT MACHINE SYSTEM REQUIREMENTS.......................................................................................................11
System Requirements using Microsoft Visual Studio .NET .............................................................................11
System Requirements using the Microsoft .NET Framework SDK..................................................................12
System Requirements using Linux and Ximian C#...........................................................................................12
COURSE INTRODUCTION...................................................................................................................................15
INTRODUCTION TOPICS.............................................................................................................................................16
W HAT IS C# ................................................................................................................................................................17
OBJECTIVES ................................................................................................................................................................18
OUTLINE ......................................................................................................................................................................19
TOPICS NOT COVERED..............................................................................................................................................24
HOW PREPARED A RE YOU .......................................................................................................................................25
INTRODUCTIONS.........................................................................................................................................................26
COURSEWARE CONVENTIONS..................................................................................................................................27
CODE CONVENTIONS.................................................................................................................................................28
GENERAL ENVIRONMENT .........................................................................................................................................29
Class Exercise: Familiarize Yourself with the Online Documentation.....................................................30
Lab Exercise ........................................................................................................................................................31
MODULE 1: CLASSES, MAIN, CONSOLE INPUT/OUTPUT, AND OPERATORS ...........................33
M ODULE 1 TOPICS .....................................................................................................................................................34
EDITOR AND TEXT .....................................................................................................................................................35
M INIMAL C# PROGRAM ............................................................................................................................................36
C SHARP COMPILER (CSC) ........................................................................................................................................37
Class Exercise: Minimal Code.........................................................................................................................39
W HAT IS A CLASS? ....................................................................................................................................................40
THE MAIN METHOD....................................................................................................................................................41
CONSOLE INPUT AND OUTPUT .................................................................................................................................43
COMMENTS.................................................................................................................................................................45
BASIC DATA TYPES ....................................................................................................................................................46
STATEMENTS AND DECLARATIONS.........................................................................................................................47
OPERATORS.................................................................................................................................................................48
The Modulus Operator "%"...............................................................................................................................49
The Logical AND Operator "&"........................................................................................................................49
The Logical Short-Circuit AND Operator "&&" ..............................................................................................50
Increment Operators..........................................................................................................................................51
Overloaded Operators........................................................................................................................................51
Post vs. Pre Increment .......................................................................................................................................52
M ODULE 1 REVIEW....................................................................................................................................................53
Lab Exercise 1 .....................................................................................................................................................54
MODULE 2: DATA TYPES AND VALUE TYPE VARIABLES .................................................................55
M ODULE 2 TOPICS .....................................................................................................................................................56
DECLARING VARIABLES ...........................................................................................................................................57
VARIABLE NAMING...................................................................................................................................................58
TWO CATEGORIES OF DATA TYPES.........................................................................................................................59
BUILT -IN TYPES (SIMPLE TYPES) .............................................................................................................................60
CLS COMPLIANT SIMPLE TYPES .............................................................................................................................61
VALUE TYPES VS . REFERENCE TYPES ....................................................................................................................62
SIMPLE VALUE TYPES...............................................................................................................................................63
Copyright 2002 Third Millennium, LLP
C# Programming (Courseware #10010B)
http://www.thirdm.com - phone: (781)674-9720
3
Contents
VB6 versus C# Data Types................................................................................................................................63
C++ versus C# Data Types................................................................................................................................64
Java versus C# Data Types................................................................................................................................64
Value Types and Storage ...................................................................................................................................65
The bool Value Type.......................................................................................................................................66
Signed Integral Value Types .............................................................................................................................67
Unsigned Integral Value Types .........................................................................................................................68
The char Value Type.........................................................................................................................................69
Floating Point Value Types ...............................................................................................................................70
LITERALS.....................................................................................................................................................................71
Literal Suffixes ..................................................................................................................................................72
Hexadecimal and Scientific Literals ..................................................................................................................73
Contents
M ODULE 5 TOPICS .................................................................................................................................................. 122
LOGICAL OPERATORS............................................................................................................................................. 123
IF................................................................................................................................................................................ 124
if/else................................................................................................................................................................125
SWITCH/ CASE ........................................................................................................................................................... 126
WHILE........................................................................................................................................................................ 127
do/while ...........................................................................................................................................................128
FOR ............................................................................................................................................................................ 129
FOREACH .................................................................................................................................................................. 130
JUMP STATEMENTS................................................................................................................................................. 132
continue............................................................................................................................................................133
break ................................................................................................................................................................134
goto..................................................................................................................................................................135
return................................................................................................................................................................136
throw................................................................................................................................................................137
Contents
U SER-DEFINED EXCEPTION SCENARIO................................................................................................................ 182
MissingSalaryException..................................................................................................................................183
Handling Exceptions........................................................................................................................................184
Nested try/catch blocks....................................................................................................................................184
Contents
U SING AN ENUM...................................................................................................................................................... 240
SYSTEM.TYPECODE ENUM .................................................................................................................................... 241
TypeCode Example .........................................................................................................................................242
Contents
A SUBCLASS ............................................................................................................................................................ 297
The SalaryEmployee Class..............................................................................................................................298
The Director Class...........................................................................................................................................299
The HourlyEmployee Class.............................................................................................................................300
Contents
Example: Declaring, Instantiating, and Invoking a Delegate..........................................................................354
Example: Invoking Delegates One at a Time ..................................................................................................355
Contents
ATTRIBUTE SYNTAX............................................................................................................................................... 412
ATTRIBUTE TARGETS............................................................................................................................................. 413
PRE -DEFINED ATTRIBUTES ................................................................................................................................... 414
CLSCompliantAttribute...................................................................................................................................415
SerializableAttribute........................................................................................................................................416
WebMethodAttribute.......................................................................................................................................417
XMLDOCUMENT...................................................................................................................................................... 445
XMLTEXT READER AND XMLVALIDATINGREADER.......................................................................................... 446
ValidationEventHandler ..................................................................................................................................447
Contents
Contents
Although any editor will work, we recommend UltraEdit since it is not very expensive
and has built in support for syntax highlighting in C#. A 45-day trial version is available
for free at http://www.ultraedit.com.
The .NET Framework SDK should modify the PATH environment variable at install time.
To ensure that the path has been setup correctly, logout and log back in using the student
account. Open a new Command Prompt window and type:
csc /?
If the command responds with a list of options, then the PATH environment variable has
been correctly modified. If the command responds with a message such as 'csc' is not
recognized as an internal or external command, operable program or batch file, then the
PATH environment variable is incorrectly modified.
If the PATH is not properly modified because the option was not selected at install time,
it is important tha t the PATH environment variable is modified to include the path to
csc.exe. This can be done in the System Control Panel under the Environment tab on
NT 4 or the Advanced tab (press button labeled "Environment Variables") on Windows
2000. You must modify either the User's PATH or the System's PATH. It is better to
modify the System's PATH because that will affect all user logins for the machine (in
case a student logs in with a different account). To locate the directory that contains
csc.exe you can use Start: Search: For files or folders. It should be located in a
directory like:
C:\WINNT\Microsoft.NET\Framework\v1.0.3705
Contents
Introduction
Introduction
C# Programming
C# Programming
Course Introduction
Introduction
Introduction Topics
n What
is C#
n Objectives
n Outline and Modules
n What's Not Covered
n Prerequisites
n Introductions
n General Environment
C# Programming
Slide 3
Introduction Topics
This chapter includes a general overview of C#, the course objectives, a list of course
modules, the prerequisites, general material layout, and the student environment.
The outline for this course is the list of module titles. This introduction sets the
expectations of the topics that will be covered in the course by reviewing the module
chapter titles. A module is similar to a chapter but is designed to be used as an
independent learning unit. Each module is designed to be independent of other modules,
but due to the C# programming language's complexity, many modules assume
understanding of topics covered in previous modules.
This module also introduces the courseware conventions, coding conventions, and
includes an in class instructor led exercise to locate and use the .NET Framework and C#
language online documentation found on the computer (not the Web).
This course introduction module ends with a lab exercise which students will work on
their own to locate topics in the online documentation. This exercise is designed to
familiarize students with the classroom and computer environment and requires no
coding.
Introduction
What is C#
n
n
n
n
n
n
Slide 4
What is C#
C# is a programming language specifically designed for Microsofts .NET Framework.
The C# programming language was jointly submitted as a proposed standard to ECMA,
an international standards organization, on October 31st , 2000 by Hewlett-Packard, Intel
Corporation, and Microsoft. The ECMA General Assembly of December 13th , 2001
approved Standards ECMA-334, C# (C sharp) Language Specification, and ECMA-335,
Common Language Infrastructure.
C# complies to the CLS. CLS is the Common Language Specification, which allows
many languages that comply with this spec in order to interoperate with each other at
design and runtime. For example, you can write a class in C++ with Managed Extensions
extend it in VB.NET and then extend it again in C#. This is not exclusive to Microsoft
languages. Theoretically in the future you can write a Perl.NET class extend it or use it
from SmallTalk-2000 (SmallScript) and extend it again in Fijutsu COBOL for .NET.
ASP.NET offers the ability to write full blown C# (similar to what is capable in JSP with
Java) and now also full blown VB (not just VBScript) with the advantage of a compiled
instead of interpreted language for improved performance of your server-side logic on
behind your web pages.
C# can be used to solve many problems, from notebook applications to very large server
systems.
Visual C++ is known for its raw power, but unfortunately with power comes complexity
and complexity brings less productivity. Visual Basic is known for its high productivity
RAD (Rapid Application Development) capabilities, but with that comes less power and
control. C# has been designed to fit between the power of C++ and the simplicity of VB.
C# merges the high productivity with raw power.
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720
Introduction
Objectives
n Understand
C# Language Fundamentals
n Use .NET objects and classes
n Define custom structs, enums, objects and
classes
n Design classes with properties, methods,
indexers, and events
n Communicate over the internet and web
n Manipulate XML
C# Programming
Slide 5
Objectives
By the end of this course you will have a good understanding of the C# language
fundamentals. You will be able to use the .NET Framework, class library (FCL), define
custom types, and write classes with properties, indexers, methods, and events. You will
also be able to use C# to communicate over the internet and web. Finally, you will be
able to use C# to read, traverse, and generate XML.
Introduction
Outline, Part 1
Modules 1 to 4
Classes, Main, Operators, Input/Output
2. Data Types and Value Type Variables
3. Reference Type Variables
4. Strings and Regular Expressions
1.
C# Programming
Slide 6
Outline
The course is broken up into five parts. Each part consists of 4 to 5 modules each. Each
part will typically take one day including time to work on the included lab exercises and
any additional exercises provided by the instructor.
Module 1: Classes, Main, Operators, Input and Output. In this module we will be
setting up environment: either Visual Studio.NET or an editor and command line
compiler in order to test the canonical HelloWorld program. We will learn the building
blocks and a starting point of a C# application. We will learn basic console input and
output. Finally, we will cover the basic operators used in arithmetic, string, and Boolean
operations.
Module 2: Data Types and Value Type Variables We will discuss the difference
between value and reference types, initializing variables, boxing/unboxing. We will also
learn that in C#, everything is an object.
Module 3: Reference Type Variables In this chapter we introduce the different types of
reference variables. These include strings, classes, interfaces, and delegates.
Module 4: Strings and Regular Expressions In this chapter we will cover some of the
built in functionality of strings and use simple regular expressions to search for a pattern
in a string.
Introduction
Outline, Part 2
Modules 5 to 9
5.
6.
7.
8.
9.
C# Programming
Slide 7
Module 5: Branching and Conditional Looping This module covers the basic if,
while, for, foreach, and switch/case constructs.
Module 6: Using Existing Classes and Objects In this module we look at the Random,
Math, File , and FileInfo classes that are available in the .NET Framework class
library. This module is designed to get you more comfortable with using classes and
objects before we design our own.
Module 7: Exception Handling In this module we learn how to trap errors and handle
them using try/catch/finally blocks. We will also throw our own exceptions when
something unexpected happens enabling the caller to handle the exception.
Module 8: Using Arrays This chapter teaches us how to create and use one dimensional
and two dimensional arrays of various data types.
Module 9: Using Collections Here we learn how to create dynamic arrays by using
the .NET Framework collection classes such as ArrayList, Stack, Queue, and
Hashtable.
Introduction
Outline, Part 3
Modules 10 to 13
Structs and Enums
11. Classes, Fields, and Properties
12. Methods, Constructors, and Indexers
13. Inheritance and Virtual Methods
10.
C# Programming
Slide 8
Module 10: Writing Structs and Enums In this module we will build C++ like structures
and enumerators and use structs and enums in the .NET Framework Class Library.
Module 11: Classes, Fields, and Properties This chapter will focus on writing our own
classes. We will build struct- like classes with fields and Properties to create state. We
will learn how to use the static, readonly, and const modifiers. We will learn the
different access modifiers for members: public through private.
Module 12: Methods, Constructors, and Indexers In this chapter we will establish
behavior for our objects. Methods allow objects to perform actions. Constructors allow
our objects to be created with special initialization routines. Indexers allow our objects to
behave like arrays and hash tables.
Module 13: Inheritance and Virtual Methods In this module we will learn how to
subclass a base class to reuse code and allow for polymorphic behavior through virtual
method invocation. We will also learn how to overload operators so our objects can have
additional object-oriented behavior when used with C#s built- in operators.
Introduction
Outline, Part 4
Modules 14 to 17
Interfaces
15. Delegates and Threads
16. Using Windows Forms to Write a
Windows Application
17. Events
14.
C# Programming
Slide 9
Module 14: Interfaces In this module we will create polymorphic behavior using
unrelated classes regardless of their hierarchy. This is a powerful feature of any language
that allows us to declare behavior semantics without forcing any specific implementation.
We will also use the .NET Framework interfaces to create an object that can be used by
the foreach loop to iterate through its members.
Module 15: Delegates and Events - creating a first class component with events
(properties and methods)
Module 16: Using Windows forms to write a Windows Application- This chapter focuses
on the basic classes required to create a Windows GUI (Graphical User Interface) for
your application using forms and controls.
Module 17: Events This chapter teaches us how to respond to and raise events in our
GUI and non-GUI applications.
Introduction
Outline, Part 5
Modules 18 to 21
Namespaces, Assemblies, and Writing
Class Library DLLs
19. Attributes and Preprocessor Directives
20. Networking
21. XML Manipulation
18.
C# Programming
Slide 10
Module 18: Namespaces, Assemblies, and Writing Class Library DLLs - Focusing on
creating class libraries, we will use namespaces which are important for complex projects.
We will also create our own reusable libraries and store them in dynamic link library
(DLL) files as private class libraries. We will also learn how to create shared libraries by
registering our library in the GAC (Global Assembly Cache).
Module 19: Attributes and Preprocessor Directives This module focuses on using a new
declarative programming feature called attributes. Attributes allow meta- information to
adorn constructs such as classes and methods. We will see examples of .NET Framework
Class Library attributes and create our own custom attributes. C# also has compiler
emulation of certain preprocessor directives familiar to C++ programmers. We will learn
how to use preprocessor directives to conditionally compile parts of our code.
Module 20: Networking Critical in today's applications, this chapter covers some basic
classes for DNS, URL, and IP address functionality. We will also use classes to connect
to web servers and download content from the web.
Module 21: XML Manipulation XML has become the universal data format for
interoperability. This chapter looks at the built- in C# language functionality such as
XML documentation, and DOM manipulation. We will also use the .NET Framework to
serialize and persist our objects using SOAP and XML Schema serialization formats.
Introduction
Basics
n Detailed coverage of Visual Studio.NET
IDE, such as debugging, IDE macros
n Unsafe Code
n Microsoft Intermediate Language (MSIL)
n Advanced C#
C# Programming
Slide 11
Introduction
C++
Java
Visual Basic
Perl
n Familiarity
C# Programming
Slide 12
Introduction
Introductions
n Name
n Programming
experience
n Job responsibility
n Current or future projects that relate to C#
n Reasons for enrolling in the course
C# Programming
Slide 13
If you have only worked with typeless scripting languages such as VBScript, JavaScript,
and Perl, you may have a challenging time with C#, unless you have used the more
complex features in these languages such as VBScript classes, or object-oriented
JavaScript features, or object-oriented Perl modules.
If your only experience with computers is writing HTML, this does not qualify for
programming experience unless you have programmed JavaScript blocks imbedded in
HTML using the <script> tag.
Introductions
This is an opportunity for each of the attendees to give the instructor some background to
why you are attending this course. This information is important for the instructor to fine
tune the delivery to the whole class experience level.
Introduction
Courseware Conventions
n
<Bold Courier>
optional in brackets: [Bold Courier]
comments: // Bold Courier
erroneous code: Bold Courier // Error
Symbols
Construct definitions from the .NET documentation or
.NET class introductions are followed by:
C# Programming
Slide 14
Courseware Conventions
These conventions are used in this book so you can identify the code examples,
intentionally erroneous code used to demonstrate when certain statements fail, optional or
placeholders, and comments. Courier font is used to represent code. Code in italics or
angle brackets is used as place holders. When describing syntax, square brackets signify
optional code such as parameters or modifiers.
There is a special symbol used to identify .NET Framework classes, types, methods, and
other constructs that can be further researched in the .NET Framework class library
documentation. Use of this symbol can also help you distinguish the material external to
C# and found in the .NET Framework from aspects of the language itself. It is important
to remember that the C# language was designed from the start to run inside the .NET
Framework runtime and therefore, many of C#'s functionality is intertwined with
the .NET Framework.
Another note is that whenever you see the .NET Framework symbol, this should also
remind you that these constructs are available not only to C# programmers but also,
VB.NET, Visual C++ with Managed Extensions, and even other languages designed to
run in the CLR (Common Language Runtime) such as ActiveState's Perl.NET and Fujitsu
COBOL.
Introduction
Code Conventions
n curly
n
n
C# Programming
Slide 15
Code Conventions
This course is designed to follow the Microsoft C# coding conventions whenever
possible. In order to fit more source code example text on the slides, the end-of- line open
brace convention is used instead of the Visual C# default next line open brace.
If you are using Visual Studio.NET and you do not want to use the Microsoft default, you
can customize the environment by choosing Tools: Options: Text Editor: C#: Formatting:
Leave open braces on same line as construct.
Camel casing is used to declare local and private variable and methods. Public constructs
such as classes, methods, properties, and public fields use the Pascal casing convention.
These conventions have replaced older coding conventions such as using underscore and
Hungarian notation. Please refer to the .NET Frame work documentation topic
under .NET Framework Developer Specifications called .NET Framework Design
Guidelines for more details.
Introduction
General Environment
n Class
Hours
n Lecture and Class Exercises
n Lab Exercises (on your own)
n Breaks and Lunch
n Restrooms, Phones, Food, and other
Facilities
n Computers, Login Accounts, etc
n Questions
C# Programming
Slide 16
General Environment
This course is designed to be a mix of lecture (which includes class exercises) and lab
exercises that follow. The class exercises allow you to follow the instructor during
demonstrations to become familiar with a specific topic. At the beginning there are
several class exercises. As the course progresses, you will do most of the exercises on
your own.
The lab exercises are at the end of each module.
Introduction
Class Exercise
(with the instructor)
n Find
Slide 17
Introduction
Lab Exercise
(on your own)
n Find
n Find
n Find
C# Programming
Slide 18
Lab Exercise
The purpose of this exercise is to familiarize you with the online documentation. This
exercise requires no programming.
Using the documentation available on the computer, find the documentation on the
System.Console class.
How do you read in from standard input? Don't worry about the code you must write,
just look for the appropriate method.
Find the appropriate class or method for writing to standard error.
Find the Math class. The Math class is located in the System namespace. The square
root function is found in the Math class.
Ask your instructor for help if you are unable to locate any of these items.
This exercise will help you become familiar with the online documentation, which is
critical to exploiting the full power of C# and the .NET Framework. Knowing how to
navigate and understand this documentation is one of the most important skills a C#
programmer can have.
Module 1
Classes, Main, Console I/O,
Operators
C# Programming
Module 1 Topics
Classes, Main, Console Input/Output, and Operators
n
n
n
n
n
n
n
n
Set up environment
Write, Compile, and Run a minimal C# program
Understand the purpose of a class
The Main method
The System namespace
Use Console input and output
Comments
Basic Operators
C# Programming - Classes, Main, Console I/O, Operators
Slide 2
Module 1 Topics
In this module, we will begin by getting comfortable with our environment, by either
opening up Visual Studio.NET or an editor and writing our first program together. We
will then compile, and run the minimal "Hello World" program. This class exercise will
get you comfortable with the programming environment and give you the opportunity to
set up or fine tune your system.
Once we have compiled our first program, we will discuss the purpose of a class. We
will learn how a class is used as a template for creating an object. It is also the container
for our Main method.
The Main method is the starting point for our program. We will learn the different
signatures possible for the Main method.
The System namespace is part of the .NET Framework where many of our standard
types can be found such as String, Object, and DateTime .
The Console class is useful for input and output. We will use the ReadLine and
WriteLine methods of the Console class as well as the Error property to access
standard in, standard out, and standard error streams.
We will learn the three types of comments: end-of- line, multi- line, and XML
documenting comments.
Finally, we will cover the basic operators for arithmetic, logic, string, and assignment
operations.
C# Programming (Courseware #10010B)
34
C# is Case Sensitive
Whitespace and new lines are mostly ignored
Layout:
Start with zero or more using statements
and/or namespace blocks
Followed by one or more classes, structs,
enums, interfaces, and/or delegates
Any text editor will work: notepad, ultraedit, etc
C# Programming - Classes, Main, Console I/O, Operators
Slide 3
Minimal C# Program
class Minimal
{
static void Main()
{
System.Console.WriteLine("Hello");
}
}
n Save
n Note:
Slide 4
Minimal C# Program
Here we are declaring a class called Minimal. Inside our class we have a Main method.
The Main method must be spelled with a capital M and must be preceded by the static
modifier. Immediately preceding the method name Main is the return type of this method.
The return type for Main can be either void (returns nothing and return statement is
implicit at the end of the block) or int (must return a valid int at the end of the Main
method. Example: return 1;)
Our program must include one Main method for the program to be executable. The Main
method may inc lude an optional string[] for command line arguments. Arrays are
covered in a later chapter.
Here are two other examples of what you can type. The using statement allows you to
abbreviate the WriteLine statement.
using System;
class Minimal2
{
static void Main()
{
Console.WriteLine("Hello");
}
}
example files:
mod01_main\minimal.cs
mod01_main\minimal2.cs
>csc Minimal.cs
output generated: Minimal.exe
n Using
Visual Studio.NET
Slide 5
All three basically do the same thing. The using declaration allows access to other
namespaces and classes without having to fully qualify the
Namespace.Classname.Method.
example files: mod01_main\minimal3.cs
Visual Studio.NET is a fully functional IDE for C# development and no special setup is
required to compile.
Command line:
>Minimal
n
n
Slide 6
To run the program, simply type the name of the executable, in this case Minimal, at the
command line and hit enter. If you are using Visual Studio, click on the Debug menu and
either use "Start" or "Start Without Debugging". The second choice is better when
testing console applications. Later we will see how you can add two lines to the end of
the Main method to pause the program before it terminates by using the
Console.ReadLine. That way you can use "Start" (with debugging).
Note: you must compile this program on a machine with either Visual Studio.NET
installed or just the .NET Framework SDK. Since the .NET Framework SDK is smaller
and has less system requirements, this may be your choice. The SDK Beta 2 only runs on
Windows NT, Windows 2000, and Windows XP. To execute the program, you do not
need the SDK, you can run the program on a computer with .NET Framework
redistributable package installed. The redistrib utable runs on Windows 98 and above.
Check http://msdn.microsoft.com/net for the latest information and downloads.
Slide 7
Once the file has been entered, compiled, and executed (tested), change the using
statement to:
using System;
You will need to make a change the WriteLine statement as well. The line should read:
Console.WriteLine("Hello");
What is a Class?
n A class
is a unit of code
nA
Slide 8
What is a Class?
A class is a unit or capsule of code. All of the variables and methods inside a class are
called members. These members are encapsulated inside the class.
A class is not only a capsule of code but is also a template for instantiating objects
(instances). Objects are discussed later in more detail.
A class is a data type. You can use a class type when declaring a variable. Since
variables in C# must always be declared with a specific type, you can use any class name
as the variable type. The next two modules cover all of the intrinsic data types available
in C# in detail.
static is used in both VB and C++ to imply that it sticks around like the static
electricity that sticks a sock to a shirt after coming out of the dryer. C# has a similar
meaning for the word static. Static methods, like Main, are always available. You do not
need to instantiate the class to invoke a static method. Nor do you need to worry about it
going away. The opposite of a static method is an instance method. Both are members,
but the static method "belongs to" the class where an instance method "belongs to" an
object.
Since instance methods "belong to" an object, they are not available until we create an
object. When the object reference is lost, the object goes away (it is actually garbage
collected). Once you loose access to your object, you can no longer invoke its instance
methods. Static methods, like functions, don't require objects to invoke.
starting point
n Is static because it is executed directly
The runtime environment will not create an
object from your class unless you explicitly do
so in your code
n Does
Slide 9
Arrays and methods are covered in more detail in later modules. The second choice uses
a string array called argv to read in command line arguments. The third and forth
choices allow you to return zero as an exit code indicating that no error occurred, or by
returning a non-zero such as one or two to indicate that a certain error occurred during
execution. Error codes are commonly used when writing command line utilities in UNIX.
There are several other possible signatures for your Main method. You can combine the
second and third choices to enable command line arguments and a error code. You can
also expose the method with higher access visibility using internal, protected or
public modifiers in front of the static modifier. If no access modifier is specified,
such as in our example, the Main method is private. We will cover access modifiers in
more detail later.
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720
System.Console.WriteLine
n
Slide 10
The Console's In, Out, and Error properties can be used for UNIX like piping as well.
When you add a using System; declaration to the beginning of a source code
document, the compiler will automatically search the System namespace when trying to
find classes that your code refers to. Therefore you do not need to type
System.Console to refer to the Console class, you only need to type Console.
The WriteLine method comes in several forms. We are using it to print a single string.
Other versions allow you to use a formatted string with placeholders for objects similar to
the C language's printf function.
n Output
Console.Write("my output");
object
Console.WriteLine("my output");
Console.WriteLine("my format {0}", var);
Console.Error.WriteLine("my output");
Slide 11
Redirecting standard error to a log file is possible in the NT/2000/XP console which
behaves very similar to a UNIX console. Attempting to redirect standard error on
Windows 98/ME using the above execute command will fail.
example files:
mod01_main\error.cs
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720
objects
Slide 12
Because the Console.WriteLine method uses the standard output stream by default the
following two lines have identical effect:
Console.WriteLine("my output");
Console.Out.WriteLine("my output");
You can add the following two lines to the end of the Main method of a Console
application being developed in Visual Studio.NET in order to use the Debug > Start
menu command instead of Debug > Start Without Debugging:
Console.Write("program end. hit enter:");
Console.ReadLine();
Comments
// this is an end of line comment
/* this is a
multi-line comment */
/// <remarks> this is an XML
/// documentation comment</remarks>
Slide 13
Comments
Here is a commented version of the Minimal program:
using System;
// Minimal is the class name
class Minimal
{
// Main is the starting point of my program
static void Main()
{
/* Console.WriteLine is short for
* System.Console.WriteLine
* which is possible because this source code
* file starts with a using System; declaration
*/
Console.WriteLine(Hello);
} // end of Main
} // end of class declaration
Module 21: XML Manipulation covers the XML documentation comments in more detail.
example files:
mod01_main\comments.cs
a sequence of characters
a whole number
either true or false
string
int
bool
string message;
message = "hello";
Console.WriteLine(message);
n
Slide 14
by a semi-colon ";"
if (x > 5) y = 10;
n Sometimes
terminated by a block { }
if (x > 5) { y = 10; }
n Can
Slide 15
Using blocks allow you to create a compound statement. In other words, a compound
statement is a statement that is made up of other statements.
if (x > 5)
{
y = 10;
z = 15;
}
Operators
n Arithmetic
n Logical
n Bitwise,
Shifting
+
&
&
|
|
*
^
^
/ %
! && ||
~ << >>
n String
+
n Increment, Decrement ++ -n Relational
== != < > <= >=
n Assignment
=
+= -= *=
/= %=
&= |= ^= <<= >>=
C# Programming - Classes, Main, Console I/O, Operators
Slide 16
Operators
This is a list of common C# operators broken into categories. We will cover a few
arithmetic, logical, increment, and assignment operators.
+
*
/
%
&
|
^
!
&&
||
&
|
^
~
<<
>>
+
Arithmetic
add
subtract
multiply
divide
modulus
Logical
AND
OR
XOR
not
short-circuit AND
short-circuit OR
Bitwise, Shifting
bitwise AND
bitwise OR
bitwise XOR
bitwise compliment
bitwise shift left
bitwise shift right
String
concatenation
++
-==
!=
<
>
<=
>=
=
+=
-=
*=
/=
%=
&=
|=
^=
<<=
>>=
Increment, Decrement
auto-increment
auto-decrement
Relational
equals
not equa ls
less than
greater than
less than or equals
greater than or equals
Assignment
assignment
add (or concatenate) and assign
subtract and assign
multiply and assign
divide and assign
modulus and assign
AND and assign
OR and assign
XOR and assign
bitwise shift left and assign
bitwise shift right and assign
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone (781) 674-9720
Operator Examples
n Modulus
int
int
int
int
apples = 14;
people = 3;
perPerson = apples / people; // 4
leftover = apples % people;
// 2
n Logical
Slide 17
n Left
Slide 18
Don't worry if you do not understand the access of the Length property. We will cover
using objects and properties in more detail later. This is only to demonstrate the fact that
the right hand side of the operation will result in an error if message is null. The shortcircuit operator prevents the right hand side from being evaluated by testing the left hand
side first.
Question: What would happen if the && was replaced with an & operator?
Answer: An error would result. If the message is null then the first test in front of the
&& returns false. Since the result of a logical AND operation requires both to be true,
the short circuit operator skips the evaluation of the right hand side. If the && was
replaced with a single &, the right is always evaluated. If you try to access the Length
property of string that does not exist (null) C# returns a runtime error.
example files:
mod01_main\shortcircuitand.cs
int counter = 5;
counter = counter + 1;
counter += 1;
counter++;
// counter=6
// counter=7
// counter=8
n The
Slide 19
Increment Operators
There are several ways to increment a variable. The traditional way (counter = counter
+1) the short cut (counter += 1) and the auto- increment (counter++). The + operator
when used with numbers does an arithmetic operation. When used with strings, the +
operator is overloaded to perform string concatenation.
Overloaded Operators
C# allows you to overload operators when you define your own types to perform the
appropriate behavior. We will cover operator overloading in Module 13: Inheritance and
Virtual Methods.
example files:
mod01_main\increment.cs
// displays 5
n Pre-increment
int counter = 5;
int item = ++counter;
Console.WriteLine(item);
// displays 6
Slide 20
example files:
mod01_main\prevspost.cs
Module 1 Review
Classes, Main, Console Input/Output, and Operators
n
n
n
n
n
n
n
You can use any editor and the command line csc compiler or the
Visual Studio.NET to develop C# applications
The purpose of a class is a container of code and a template for an
object
The Main method is a static method and serves as the starting
point of your application
The System namespace contains many useful classes and types
including the Console class
Use Console for input: ReadLine and output: WriteLine
3 types of comments // single-line, /* multi-line */, and
/// XML documentation
Basic operators include + , - , * , /, and & to provide arithmetic
Boolean, and string operations
C# Programming - Classes, Main, Console I/O, Operators
Slide 21
Module 1 Review
In this chapter we learned how to compile a simple C# program with either the command
line or the Visual Studio environment.
We also learned about classes, the Main method, and the System.Console class.
For basic input and output, the Console class comes with static methods for reading and
writing lines of text.
C# allows for three types of comments. Two types from C++ and a third type for XML
documentation which is covered in more detail in the XML module.
We were introduced to basic operators for arithmetic, logical, string, and assignment
operations.
Lab Exercise 1
(on your own)
n
n
Slide 22
Lab Exercise 1
Step #1: Rename the class in your source file, but do not rename the file. For example
call the class Hello and keep the source file name Minimal.cs. Compile and test. Does
it still work? There are no rules for naming filenames after class names in C# like there
is in Java.
Step #2: When you compile Minimal.cs, try to see if the resulting exe file can be called
something other than Minimal.exe, for example try to see if you can generate the
executable called First.exe. If you are using csc, you should use the command line
options. If you are using Visual Studio.NET, use the project properties.
Step #3: During the class exercise you created an alias for System.Console, try doing
it again on your own. This time call it stdout.
Step #4: If you finish early, try experimenting with math operators doing basic math
using int types.
Module 2
Data Types and Value Type
Variables
C# Programming
Module 2 Topics
Data Types and Value Type Variables
n Learn
Slide 2
Module 2 Topics
In this module, we will learn more about declaring variables. We will also learn the
difference between the two categories of data types: value type and reference type.
We will cover the complete list of the 15 built- in data types.
We will also be introduced to struct and enum types, both of which are value types. We
will spend more time in a later module creating our own structs and enums.
Declaring Variables
n
n
datatype varname;
string x;
n
Slide 3
Declaring Variables
Detailed coverage of the different data types follow. This slide uses string (a sequence
of characters) and int (a 32 bit integer) for examples of declaring variables.
When you declare a variable in C#, you must specify the data type. In VB6 variables can
be declared without a data type. This is called loosely typed or weak data typing. Many
scripting languages such as Perl, VBScript, and JavaScript are loosely typed. C# is
strongly typed. All variables must be declared with a specific data type.
You may declare multiple variables together separated by commas. All variables
declared together take on the same type. Also, you may assign an initial value to the
variable as in the example:
int y = 5;
You may not declare a variable twice in the same block. Local variables are declared in a
method block or inside a nested block such as a loop block. Member variables are
declared in a class block.
In Visual Basic 6 and older you are not allowed to declare and assign an initial value to a
variable in the same statement except for constants. VB.NET allows the same type of
declare and initialize in the same statement, just like C#.
For the purpose of discussing variables, we will focus on local variables for the length of
this module. These variables will be declared in the Main method.
Variable Naming
n
Naming convention
Use camelBack for any variable that are hidden (local
and private variables)
Use PascalStyle for variables that are exposed with
the public modifier
n
n
n
Slide 4
Variable Naming
PascalCase uses capital letters for the first character in each word and avoids underbars.
For example:
Employee , BackupFile, OpenNextRecord, FirstName
camelCase uses capital letters for each word except the first word in the variable name.
For example:
employee , backupFile, openNextRecord, firstName
Private variables, method parameters, local variables, private methods and other private
members not exposed to the outside should follow camelCase. Anything exposed outside
of the class should follow the PascalCase naming convention. It is important when
writing C# code that is CLS compliant that public members do not differ in case alone.
CLS allows multiple language access to a common class. Since Visual Basic is case
insensitive, it can not differentiate between two public methods that differ in case alone.
Private data and behavior names do not need to follow any CLS compliance since they
are not exposed to other languages such as Visual Basic.
.
Types
Types
Slide 5
Other conventions:
- do not use an underscore in class and interface names
- do not prefix classes with the letter C (common in Visual Basic)
- do prefix interfaces with the letter I (also common in Visual Basic)
- do suffix exception classes with Exception (common in Java)
- do suffix attribute classes with Attribute
- do use nouns when naming classes
- do use verbs when naming methods
Please refer to the .NET Framework documentation topic under .NET Framework
Developer Specifications called .NET Framework Design Guidelines for more details
Universal
object (anything and everything)
Text based
string (sequence of characters)
char (a single character)
Logical
bool (true or false)
Numeric
int, float, double, etc...
C# Programming - Data Types and Value Type Variables
Slide 6
char
byte
short
int
long
float
double
decimal
string
object
Slide 7
Slide 8
Slide 9
C#
Byte
Double
Decimal
Single
Integer
Long
Boolean
Currency
Date
Object
Variant
String
byte
double
decimal
float
short
int
bool
decimal
DateTime
object
object
string
Relationship
identical
identical
almost identical
different name
different name
different name
different name, more restrictive
different name, bigger range in C#
different name, C# uses the .NET Framework struct
VB6 Object is more restrictive
similar
similar
Visual Basic programmers must remember that C# is case sensitive. These data types
must be declared in all lower case.
C++ versus C# Data Types
Because C++ is machine dependant and the use of sizeof is required to find out the
range and size of a fundamental data type, the chart below will not always be accurate.
For example an int in C++ may be 16 bits or 32 bits. In C# it is always 32 bits.
C++
C#
bool
char
short
int
long
float
double
unsigned short
unsigned int
unsigned long
bool
char
short
short or int
int or long
float
double
ushort
uint
ulong
Relationship
more restrictive
different size (8 bit vs. 16 bit)
identical
identical
identical
different name
different name
C#
boolean
byte
short
int
long
char
float
double
bool
sbyte
short
int
long
char
float
double
Relationship
different name
different name
identical
identical
identical
identical
identical
identical
y ++;
6
y
y is affected
n x and y stored directly on the stack
n Fast, less memory required than objects
n Only
Slide 10
example files:
mod02_value\value.cs
Slide 11
example files:
mod02_value\bool.cs
short x = -5;
int y = 200123;
long z = x * y;
Slide 12
example files:
mod02_value\signed.cs
ushort x = 64000;
char letter = 'A'; // character 65
uint y = letter; // y = 65
ulong z = x * y;
C# Programming - Data Types and Value Type Variables
Slide 13
example files:
mod02_value\unsigned.cs
Slide 14
example files:
mod02_value\char.cs
n
n
Slide 15
Literals
n bool
Slide 16
Literals
There are only two valid literals Boolean values: true and false. Since these are
reserved words they must be all lower case.
Whole numbers are automatically evaluated as int type data except when you assign it to
a smaller data type or use a suffix such as L for long.
Fractional literal numbers (expressed with a decimal point) or numbers expressed in
scientific notation, are evaluated as double type data.
Examples of scientific no tation will be shown later.
Literal Suffixes
nM
for double
n F for float
float pi = 3.14f;
nL
Slide 17
Literal Suffixes
Literal suffixes are not case-sensitive.
Although it is legal to use a lower case L for the literal long suffix, do not use it. Lower
case L looks very similar to the number one. The example below looks like the literal
one thousand and one, but it is actually one hundred with a lower case "L".
long badPractice = 100l;
example files:
mod02_value\suffix.cs
n Real
Slide 18
Another example:
float y = 5e3; // compile error
float y = 5e3f; // ok
example files:
mod02_value\hex.cs
Slide 19
min
0
0
0
0
0
-128
-32768
-2,147,483,648
-9,223,372,036,854,775,808
smallest non zero
1.5 10-45
5.0 10-324
1.0 10-28
max
255
65,535
65,535
4,294,967,295
18,446,744,073,709,551,615
127
32767
2,147,483,647
9,223,372,036,854,775,807
max
3.4 1038
1.7 10308
7.9 1028
precision
7 digits
15-16 digits
28-29 digits
Slide 20
For integrals (sbyte, byte, short, ushort, char, int, uint, long, and ulong)
which store only whole numbers, the range can be determined by raising 2 to the power
of the number of bits. For real numbers (float, double, decimal ) the range is based
on an internal storage formula that uses an exponent and mantissa to convert a real
number to binary. Note that real numbers always have the possibility of loss of accuracy
do to the translation to binary. This is a common problem in many languages. The
decimal type avoids this problem by storing the number as a 96 bit binary integer and
using the remaining 32 bits to store the location of the decimal point. That is why
decimals are in fact 128 bit data types but have a range similar to float which is only 32
bits. The decimal type is important for monetary data and other data which can not
loose precision. You can see IBM's web site for more information about the problem
with Java's float and double types and even the Java's java.math.BigDecimal class.
IBM has a BigDecimal class called com.ibm.math.BigDecimal available at
http://www.alphaworks.ibm.com which solves this problem.
Implicit Conversion
conversion from any type
to any other type that
requires going against the
arrows requires a cast
sbyte 8
short 16
byte 8
object
double 64
decimal 128
int 32
ushort 16
float 32
long 64
uint 32
ulong 64
char 16
C# Programming - Data Types and Value Type Variables
Slide 21
Implicit Conversion
Notice bool is absent. You may not cast to or from any of the above simple value types
to a bool type. Notice object is not a simple value type but in fact a reference type.
Any time you must traverse against the arrows during a conversion, casting is required.
sbyte small = 123;
int bigger = small;
sbyte small = 123;
uint bigger = small;
//ok
Casting
binary representation
sbyte a = -1;
a 11111111
int x = a;
11111111111111111111111111111111
x
Console.WriteLine(x); // output -1
sbyte b = (sbyte)x; //cast
b 11111111
Console.WriteLine(b); // output -1
byte c = (byte)b; //cast!!
c 11111111
Console.WriteLine(c); // output 255
C# Programming - Data Types and Value Type Variables
Slide 22
Casting
In C#, an sbyte stores 8 bits using two's complement. That means that the number zero
is stored in binary as 8 unset bits (00000000). The number one is stored as seven unset
bits and one set bit (00000001), but the number negative one is stored as eight set bits
(11111111). The first bit tells the system if the number is positive (0) or negative (1).
The range of an sbyte is -128 to 127. The range of an int is approximately negative 2
billion to positive 2 billion. But since a byte is unsigned, it can not store negative
numbers (no negative sign). For this reason, the range of a byte is 0 to 255.
When you implicitly convert an sbyte to an int, no information can be lost. The
number one stored is converted from 8 set bits to 32 set bits (still the number negative
one). When the number is cast from an int to a byte, the top 24 bits are cut off. Now
we have only 8 set bits left, but byte along with the other unsigned types do not use
two's complement, so the number is valued as the biggest byte which is the number 255.
So be careful when casting numbers.
example files:
mod02_value\cast.cs
on the stack
n/i
n/i
5
8
Slide 23
The values X and Y must be initialized before they are used. This can be done in one of
three ways.
1. Explicitly assigning the values as demonstrated above.
2. Using a default constructor call with new:
MyPoint p = new MyPoint(); // X and Y are initialized to 0 (zero)
Console.WriteLine(p.X); // prints 0
example files:
mod02_value\struct.cs
3. Writing a constructor that takes initial parameter values and assigning them in the
constructor, then using the appropriate call with new. This is very similar to class
constructors and will be covered later in more detail.
public struct MyPoint {
public MyPoint(int x, int y) {
X = x;
Y = y;
}
public int X;
public int Y;
}
type
bool
sbyte
short
int
long
byte
ushort
uint
ulong
char
float
double
decimal
System.Boolean
System.SByte
System.Int16
System.Int32
System.Int64
System.Byte
System.UInt16
System.UInt32
System.UInt64
System.Char
System.Single
System.Double
System.Decimal
example files:
mod02_value\struct2.cs
hireDate
n/i
1999
12
31
Slide 24
The assignment operator (=) is used to assign a value to the data and initialize the
variable. This assignment does not create any new objects on the heap. The assignment
simply calls a struct constructor. Constructors are covered later.
hireDate= new DateTime(1999,12,31);
example files:
mod02_value\datetime.cs
enum Suit
{
Hearts, Clubs, Diamonds, Spades
}
...
Suit card = Suit.Diamonds;
Console.WriteLine(card); // prints Diamonds
Console.WriteLine((int)card); // prints 2
C# Programming - Data Types and Value Type Variables
Slide 25
Note, the first Console.WriteLine line above prints "Diamonds" because the
WriteLine method calls the types ToString method which in the case of an enum type
results in the element's name being displayed instead of the enum's value. When cast to
an int type, we see the element's value of 2 being displayed.
More detail on enum types is discussed in a later module.
example files:
mod02_value\enum.cs
int x;
int y = x; // error
int x;
x = 5;
// definite assignment
int y = x; // ok
n
n
Slide 26
// error
The reason the above expression fails to compile is that the value of x was never
initialized. This is only a problem when you are creating local variables. Local variables
are declared in a method, property accessor, indexer accessor, or a constructor. Instance
and static variables belong to objects and classes respectively. These variables are
automatically initialized when the object is instantiated for instance variables or when the
class is loaded for static variables.
You can not assign the null value to a value type. The null value is only available to
reference types.
Module 2 Review
Data Types and Value Type Variables
n Variables
Slide 27
Module 2 Review
In this module, we learned the difference between value types and reference types.
We also went into detailed coverage of the built- in value types and were introduced to
enum and struct types.
Lab Exercise 2
(on your own)
n
Slide 28
Lab Exercise 2
Part One:
Step #1: Write a program that declares three int type variables. You can name those
variables var1, var2, and var3. Assign a different value to each variable such as 1000,
2000, and 3000.
Step #2: Create a third variable of long type. You can call that variable var4. Assign
var1 to var4. Add var2 to var4. Add var3 to var4. Print the result.
Step #3: What would happen if you tried to assign var4 to any of the int type variables?
Such as:
var2 = var4;
If you are not sure of the result, try it. Even if you are sure, try it to prove your
assumptions. If it fails, fix it.
Part Two:
Step #1: Write a program that declares two DateTime variables:
DateTime first;
DateTime second;
Step #2: Once you have declared both variables, assign the first variable today's date and
the second variable should be assigned to the value of the first.
first = DateTime.Now;
second = first;
Step #3: Print both. Change the first variable and reprint both. Change the first using:
first = first.AddDays(100);
C# Programming (Courseware #10010B)
84
Module 3
Reference Type Variables
C# Programming
Module 3 Topics
Reference Type Variables
n Compare
Slide 2
Module 3 Topics
In this module, we will understand reference types compared to value types.
The null reference is an important value fo r enabling garbage collection.
We will understand the process of boxing and unboxing value types in an object
reference.
The string and object types are important built- in types. We will cover some of the
basics of these types.
We will be introduced to the .NET Framework classes such as StringBuilder and Stack.
We will also look at user defined classes.
Finally, we will look at arrays, interfaces, and delegate reference types.
This module will give you a good overall picture of the scope of reference types available
in C#.
Reference Types
n
Slide 3
Reference Types
The object type is an alias for the System.Object class found in the .NET
Framework.
The string type is an alias for the System.String class found in the .NET
Framework.
The object and string types are the two reference types built- in to the C# language. The
remaining reference types can either be found in the .NET Framework or are user-defined.
Classes are used in C# to describe a type of "thing" or type of object. When you create
an instance of a class, you create an object. All reference variables "point-to" an instance
of a class. Class types are not the only type of variable types, though. You can have
delegates, events (which are delegates), interfaces, and array reference types, but all of
these types refer to objects instantiated from classes. The System.Array and
System.Delegate classes are instantiated at run time when you use C# array
references and delegates.
Variables in C# are used to access objects by reference. A reference is not a pointer like
C++, instead it is much safer like Java.
When you declare a variable of value type, C# allocates enough memory on the stack to
store the whole data structure. But when you declare a variable of reference type, C#
only allocates enough memory on the stack to store the reference to a potential object.
Not until you initialize the reference with a new object, will memory on the heap be
allocated to store the whole class data structure.
reference anything!
object
object
object
object
obj1
obj2
obj3
obj4
=
=
=
=
true;
// bool
255;
// int
"hello"; // string
new Employee();
n Must
Slide 4
example files:
mod03_reference\object.cs
stack
ref
ref
heap
n Data
boxing
C# Programming - Reference Type Variables
Slide 5
x = null;
y = null;
ref
ref
null
ref
null
null
5
Slide 6
Garbage Collection
Garbage collection is carried out by the runtime to free memory left from unreachable
objects in memory. The .NET Runtime (Common Language Runtime or CLR) uses a
background thread to check for instances that have gone out of scope, that were
abandoned by a null reference, or are unreachable for any reason from the code running
on the system. By using garbage collection, C# relieves the programmer from the
responsibility of tracking memory allocations and de-allocations. C++ programmers
often spend a good amount of their effort managing memory and avoiding memory leaks
instead of solving business domain problems.
example files:
mod03_reference\null.cs
Value/Reference
Storage Comparison
stack
int x = 5;
object y = 5;
n
n
n
n
ref
heap
Slide 7
Object References
StringBuilder sb, greeting;
sb = new StringBuilder("hello");
greeting = sb;
sb
ref
greeting
ref
: StringBuilder
text = "hello"
Append(more text)
sb.Append(" world");
: StringBuilder
sb
ref
greeting
ref
Append(more text)
Slide 8
Object References
Because references point to the data and are not the data itself, when you copy a
reference you do not make a copy of the data. When one of the references' data is
manipulated, the other is affected because they point to the same "thing".
StringBuilder sb = new StringBuilder("hello");
StringBuilder greeting = sb;
sb.Append(" world");
// sb is now "hello world"
// greeting is now also "hello world"
Notice in the example above, the variable sb was appended to, but the variable
greeting was also affected. Remember that value data types are not affected when a
copied variable is manipulated:
int x = 5;
int y = x;
y ++;
// x is still 5
// but y is now 6
example files:
mod03_reference\stringbuilder.cs
ref
ref
object x = w;
int y = (int)x;
object z = x;
boxing
unboxing
// boxing
// unboxing
// not boxing!
Slide 9
Notice that copying a boxed value does not copy the data, only the reference to the data:
object z = x;
example files:
mod03_reference\boxing.cs
:String
"Hello "
string name;
name n/i (not initialized)
name = "George Washington";
name
:String
"George Washington"
:String
"Hello George Washington"
Slide 10
At this point, the name variable is not null, nor does it reference a string. The name
variable is not initialized.
Assigning a value to the variable name creates the object that contains the sequence of
characters. In fact literal strings objects in your code are instantiated when the code is
loaded, before this code is reached and stored in a string pool. When this code is reached,
the reference assignment then points to the previously created object. This behavior is
not guaranteed, and another .NET implementation may create strings on the fly.
name = "George Washington";
Slide 11
example files:
mod03_reference\stack .cs
ref
ref
n/i
:Employee
name null
empId
0
:Employee
name John Doe
empId 1234
Slide 12
The following is a reference declaration. The variable e can in the future reference
(point) to an object (instance) or null (nothing).
Employee e;
The following is a reference assignment to a new instance (newly created object). At this
point the data structure is created on the heap and can be assigned attribute values.
e = new Employee();
The following code are object field assignments which store data in the object on the
heap.
e.Name = "John Doe";
e.EmpId = 1234;
example files: mod03_reference\employee.cs
C# Programming (Courseware #10010B)
96
ref
0 999
1 789
2 824
...
9 1021
Slide 13
example files:
mod03_reference\array.cs
person1
person2
person3
person4
=
=
=
=
new
new
new
new
Employee();
Contractor();
TempEmployee();
BoardMember();
Slide 14
function pointer
n Used by threads and events
n Example
ThreadStart starter = new ThreadStart(MyMethod);
...
public static void MyMethod()
{
// do something in a separate thread
}
Slide 15
Module 3 Review
Reference Type Variables
n
n
n
n
n
n
n
Slide 16
Module 3 Review
In this module we looked at the string and object reference types.
We explored garbage collection and the use of the null reference value.
We used boxing and unboxing to use object, a reference type, to refer to value data, and
return the data back again to its original state on the stack.
We looked at an example of a .NET Framework class, the Stack, and how it can be used
to hold data on the heap.
We saw an example of a user defined class type.
Finally we looked at array, interface, and delegate reference types.
This module is an overview of the different reference types we will explore in the rest of
this course.
Lab Exercise 3
(on your own)
n
n
n
n
n
n
Slide 17
Lab Exercise 3
Step #1: Using the Employee class we saw earlier as a model, write your own
Employee class. Make sure the two fields are FirstName and LastName and are both
string types.
Step #2: In a separate class called Test, write a Main method that instantiates your
Employee class three times to create three separate objects. Use the references e1, e2,
and e3 to reference them.
Employee e1 = new Employee();
Employee e2 = new Employee();
Employee e3 = new Employee();
...
Step #4: Print the first and last names for e1, e2 and e3.
Step #5: Assign the reference value of e1 to e2 and then change e2's first name.
e2 = e1;
e2.FirstName = "Max";
Step #6: Reprint all three names. Can you explain this behavior?
Module 4
Strings And Regular Expressions
C# Programming
Module 4 Topics
Strings and Regular Expressions
n Use
Slide 2
Module 4 Topics
This chapter focuses on using strings to convert to other types, clean up strings, special
string methods, and using regular expressions to search strings.
In this chapter, we will use structs, such as System.Byte and System.Int32, to
convert strings to numeric data by invoking their Parse method.
We will clean up strings with the Trim method to eliminate extra white space before and
after the text in a string.
We will use the @ symbol to write literal strings that ignore escape characters and allow
raw whitespace characters such as carriage returns.
We will examine string formatting used in the Console.WriteLine method and learn
how to use formatting special codes.
Finally, we will learn how to write regular expressions and use them in C# programs to
search for patterns in a string
String Concatenation
n Use
n Combine
literal strings
n Combine
variable strings
Slide 3
String Concatenation
Strings are useful in any language. In C, strings are character arrays. In C# strings are
immutable objects, instances of System.String.
String concatenation is the process of combining two strings to create a third string. The
plus (+) operator is used to activate concatenation. You should not use string
concatenation in a large loop or with large strings because of the wasted memory and
resources that result. You are better off using the StringBuilder class as
demonstrated earlier on page 92.
Here is an example of using StringBuilder:
string first = "John";
string last = "Smith";
string sep = " ";
fullname = first + sep + last;
Console.WriteLine(fullname);
StringBuilder sb = new StringBuilder(first);
StringBuilder full = sb;
sb.Append(sep);
Console.WriteLine(sb);
// sb is now "John Smith"
Console.WriteLine(sb);
// full is now also "John Smith"
Console.WriteLine(full);
example files:
mod04_strings\concat.cs
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720
Slide 4
Underlying Struct
sbyte
byte
short
ushort
int
uint
long
ulong
char
float
double
bool
decimal
System.SByte
System.Byte
System.Int16
System.UInt16
System.Int32
System.UInt32
System.Int64
System.UInt64
System.Char
System.Single
System.Double
System.Boolean
System.Decimal
n Use TrimStart(null)
or TrimEnd(null) to
remove whitespace only from one side
string message = " \t hello world \r\n ";
message = message.TrimEnd(null);
Console.WriteLine("[" + message + "]");
Slide 5
trim itself and receive the new string. In both examples above, the returned value is
reassigned to the original variable. You could assign the trimmed value to a new string
variable if you needed both the original string and the modified string.
example files:
mod04_strings\trim.cs
string
string
char[]
string
if (s1
if (s1
s1 = "hello";
s2 = "hello";
data = {'h', 'e', 'l', 'l', 'o'};
s3 = new String(data);
== s2) { /* this is true */ }
== s3) { /* this is also true! */ }
Slide 6
The runtime system will probably not use the same string but rather create a new instance.
The comparison of s1 and s3 will most probably be comparing two separate instances.
In Java, the second if statement would be false because Java's == operator compares
references, not string data. This can be the cause of many bugs in Java. If you want to
compare two references to see if they point to the same object in memory, use the static
Object.ReferenceEquals method. For example:
if (Object.ReferenceEquals(s1, s3)) {/*this is probably false*/}
example files:
mod04_strings\equality.cs
C# Programming (Courseware #10010B)
108
string s1 = "hello";
string s2 = "hello";
if (s1 == s2) { /* this is true */ }
if (s1.Equals(s2)) { /* also true */ }
C# Programming - Strings and Regular Expressions
Slide 7
example files:
mod04_strings\equality.cs
Escape Sequences
n "\t"
is a tab character
n "\r\n"
n What
Slide 8
Escape Sequences
\r
\n
\t
\\
\"
Slide 9
String formatting
string user = Console.ReadLine();
Console.WriteLine("Welcome {0}.", user);
int qty = 5;
string item = "hats";
objects to be inserted
into format holders
Slide 10
String formatting
If you wanted to print formatted output, you can print a format string followed by a list of
variables to insert into the formatted string. Here are two examples:
int red = 255;
int green = 0;
int blue = 204;
Console.WriteLine("<font color='#{0:X2}{1:X2}{2:X2}'>",
red, green, blue );
would print out:
<font color='#FF00CC'>
The place holder {0:X2} has two parts. The left side of the colon indicates which
variable 0, 1, or 2. 0=red, 1=green, 2=blue. The right side of the colon indicates X for
hexadecimal, and 2 for the number of digits. Thus the number 255 becomes the
hexadecimal number "FF", 0 becomes "00" and 204 becomes "CC".
decimal price = 2.05m;
int qty = 6;
decimal total = price * qty;
Console.WriteLine("price={0:C} qty={1} total={2:C}",
price,
qty,
total);
The price and total placeholders include the letter "C" after the colon in the format to
indicate currency. E = Exponential (scientific) notation, F = Fixed point, G = General, P
= Percent. For a full list of formatting codes refer to the .NET Framework documentation.
example files: mod04_strings\formatting.cs
C# Programming (Courseware #10010B)
112
Regular Expressions
n
match
n
The match
string input = "This is a test";
bool found = Regex.IsMatch(input, pattern);
if (found) {
Console.WriteLine("match found for '{0}'", pattern);
}
C# Programming - Strings and Regular Expressions
Slide 11
Regular Expressions
Regular Expressions (regex) are a powerful search mechanism that searches for patterns
in text. The UNIX world has enjoyed regex for years, recently Microsoft incorporated
regex into VBScript and now, in .NET, it is available to all .NET CLI compliant
languages including COBOL and Visual Basic.
In the basic pattern to look for above, the pattern string is two characters i and s. The
input string being searched is "This is a test". Notice that the characters i and s appear in
sequence in two places. The first appearance is in the word "This" and the second is "is".
The result of the IsMatch method is true if it finds the pattern in the search string. If it
does (anywhere) it returns a true. If it is not found, the result is false.
The Regex class and the whole System.Text.RegularExpressions namespace are much
more powerful than this simple example. This example is designed to introduce you to
the topic. O'Reilly and Associates publish a book called Mastering Re gular Expressions
by Jeffrey E. F. Friedl (with an owl on the cover).
In the next few pages we will cover some basic expressions with meta-characters and
qualifiers.
example files:
mod04_strings\regex.cs
Slide 12
Regex Meta-Characters
n Characters
char
meaning
any character
or
()
group
zero or more
one or more
zero or one
Slide 13
Regex Meta-Characters
The meta-characters in the chart demonstrate several characters that have special
meaning in a regular expression.
For example the dot (.) character represents any single character, including an alpha,
numeric, punctuation, or even a space character. Two dots (..) represent two of any
character. Therefore the regex "f..d" matches on "food", "fold", "soft drink". Notice in
the "soft drink" search string, the "f" is followed by two characters, a "t" and a space, then
followed by a "d" character.
Sequence is important. The sequence of characters must be exact. If my regex is "f..d",
then I must have one "f" followed by exactly two characters, followed by one "d". What
comes before the "f" and after the "d" is not significant. For example in the search string
"I eat food at lunch" the characters before and after "food" are not important to the
regular expression "f..d".
Quantifiers are meta-characters that determine the quantity of the character or group
before it appears. For example in the expression "fo*d" the star (*) quantifies the
character "o". This expression states that zero or more "o" characters must follow an "f"
and precede a "d" character. Therefore the "fo*d" expression matches the search string "I
eat food at lunch" because there is an "f" followed by zero or more "o" characters
followed by a "d" character. The "fo*d" would fail on the search string "fold the paper"
because the "l" appears between the "o" and the "d". The "fo*d" expression can only
match successfully if the "f", "o", "d" sequence has no other characters in it, even a space
character.
Complete Example
using System;
using System.Text.RegularExpressions;
class Test {
static void Main() {
string pattern = "f..d"; // expression
string input = "I eat food for lunch"; // search string
bool found = Regex.IsMatch(input, pattern);
if (found) {
Console.WriteLine("{0} matches {1}", pattern, input);
} else {
Console.WriteLine("{0} fails on {1}", pattern, input);
}
}
}
Slide 14
Complete Example
This example demonstrates the use of a regular expression with meta characters. If you
edit this file you can change the pattern by retyping it and recompiling.
A better file to experiment with regular expressions is the sample file grepsharp.cs.
This file contains topics that will be covered later and therefore the example code is not
displayed. The grepsharp program takes a pattern and a filename at the command line,
very similar to the Unix grep command. This will allow you to experiment with a file
called search.txt that contains the strings in the chart from the previous page.
example files:
mod04_strings\regex_complete.cs
mod04_strings\grepsharp.cs
mod04_strings\search.txt
Module 4 Review
Strings and Regular Expressions
n
n
n
n
n
n
Slide 15
Module 4 Review
In this chapter we looked at string functionality in C# including concatenation vs.
StringBuilder 's Append method.
We also looked the Parse method in each of the simple type structs in order to convert a
string to other simple types like int and byte.
We used Trim, TrimStart, and TrimEnd to clean up strings.
We examined the difference between == and .Equals and how they are often identical,
especially in immutable objects like strings.
We learned a few escape characters such as \\, \t, \n, and \r. We also learned how to use
the @ prefix to ignore escape characters and allow multi- line literal strings.
We learned the built in Format function and how it is also used by the
Console.WriteLine method.
Finally we learned how to use the Regex.IsMatch class to do use regular expressions to
search for patterns in text.
Lab Exercise 4
(on your own)
n
n
n
n
n
n
Slide 16
Lab Exercise 4
Step #1: Start a C# console project or open a new file in your editor. In the Main method,
use the variables s1, s2, and s3, create three strings. The strings s1 and s2 will contain the
literal strings:
string s1 = "I like to sail in a sailboat. ";
string s2 = "I lost my boot in the water. ";
Step #2: Using string concatenation, create s3 from the contents of s1 and s2. Make sure
that s1 is first and s2 is second.
Step #3: Use regular expressions to search all three strings individually for the pattern
"bo*t". If you find a match display a message stating you found a match for the pattern
and were you found it. Example output:
Found a match for "bo*t" in "I like to sail in a sailboat. "
If you don't find a match the output should display a negative message:
No match found for "bo*t" in "I like to sail in a sailboat. "
The output should be no match for s1 but a match for s2 and s3 because the pattern
"bo*t" searches for the letter "b" followed by zero or more letter "o" characters followed
by the letter "t". Remember, * is not a wildcard, it is a quantifier for zero or more of the
previous item.
Note, only one of the two messages should be displayed by your program for each
variable s1, s2, and s3. If you get both "Found a match..." and "No match found..."
messages for the same variable, make sure you are using an if/else statement.
if (condition)
{
// do something
}
else
{
// do something else
}
Step #4: Make a change to the program to include a search of all three strings for the
pattern "bo.t" and "boat.*boot". To separate each pattern result, add a line before
each pattern group that states something like:
Using pattern: bo*t
Include a carriage return line feed escape sequence to put a blank line in front of the word
"Using".
Note: Because we have not covered writing our own methods and using arrays, this code
may require copy-and-paste programming. Don't worry, we will cover methods and
arrays later. If you feel comfortable enough, you can try to using arrays or methods to
reduce the code required to solve this lab exercise. The solution provided does not
assume any knowledge of arrays of writing methods besides the Main method. Here is
the expected output:
Course Review
Course Review
C# Programming
C# Programming
Course Review
Course Review
Objectives Review
n Understand
C# Language Fundamentals
n Use .NET objects and classes
n Define custom structs, enums, objects and
classes
n Design classes with properties, methods,
indexers, and events
n Communicate over the internet and web
n Manipulate XML
C# Programming
Slide 2
Objectives Review
Now that you have completed this course, you should have a good understanding of C#
language fundamentals. With the fundamentals, you can learn any aspect of C#
programming from client-side, Windows GUI, server-side, Web pages using ASP .NET,
and Web services.
We covered using the .NET class library to use classes and object for manipulating files,
retrieving Web pages, using Regular Expressions, and much more.
We defined custom structs, enums, objects and classes.
We designed classes that expose properties, methods, events, and indexers. We stored
those classes in reusable DLL libraries as private and shared assemblies.
We learned how to communicate over the Internet using Uri, Dns, and WebRequest
classes.
Finally we learned how to manipulate XML using DOM objects and serialize our object
to and from XML instances.
Course Review
What's Next
Depending on your particular use of C# and
.NET you may want to look for more training
aids or courses on the following topics:
n ADO
.NET with C#
n ASP .NET with C#
n Web Services with C#
n Visual Basic .NET
C# Programming
Slide 3
What's Next
Consider continuing learning on the following topics:
ADO .NET with C#
Learn more about ADO .NET (ActiveX Data Objects) for access to databases such as
Oracle and Microsoft SQL Server using the latest trends in XML.
ASP .NET with C#
Learn more about Web site development with C# and ASP .NET (Active Server Pages).
Web Services with C#
Learn more about XML Web Services using SOAP (Simple Object Access Protocol) and
WSDL (Web Service Description La nguage) to design Web sites that communicate with
other Web sites and the next generation of EDI (Electronic Data Interchange)
Visual Basic .NET
Learn more about the next generation of Visual Basic
Course Review
Resources
n
Visual Studio
http://msdn.microsoft.com/vstudio/
Other
http://www.csharphelp.com/
http://www.csharpindex.com/
C# Programming
Slide 4
Resources
Information for C# and .NET programmers
Go to the ThirdM.com web site for information about C# and .NET trends.
http://www.thirdm.com
MSDN and Visual Studio
Microsoft's web sites include online articles and documentation on C# and the .NET
framework.
http://msdn.microsoft.com/net
http://msdn.microsoft.com/vstudio
Other Resources
There are plenty of Web sites on the Internet for C# information. You may find the C#
Help and C# Index web sites helpful.
http://www.csharphelp.com
http://www.csharpindex.com
Index
INDEX
#define, 445
#if, 445
#region, 445
#warning, 445
%, 52
&, 52
&&, 53
.NET Runtime, 66, 96, 245, 351, 413
@, 117
== operator, 114
abstract, 332
abstract class, 332
Access Levels, 272
ActiveX, 419
ActiveX DLL, 413
Application class, 384
Application.Run, 384
ApplicationException, 182, 183
Array class, 204
ArrayList, 220
arrays, 201
declaring, 201
as operator, 321
associative array, 227
Attribute class, 441
attribute targets, 435
Attributes, 433
auto-increment, 55
base, 322
base class, 309
base keyword, 329
bool, 71
Boxing, 99
break, 140
Built-In Types to .NET Framework
struct Mapping, 84
Button, 386, 387
C++, 12, 19, 24, 26, 28, 30, 37, 42, 49,
56, 69, 70, 71, 79, 93, 96, 135, 144,
149, 151, 153, 201, 208, 242, 268, 296,
347, 444
camelCase, 62
case, 132
Casting, 82
Casting references, 318
Copyright 2002 Third Millennium, LLP
http://www.thirdm.com - phone: (781)674-9720
Index
encapsulation, 149
enum
calculated values, 254
user defined, 253
enum types, 247
enumeration, 247
Equals method, 114, 115, 334
event, 397
event handler, 397, 401
EventArgs, 398
EventHandler delegate, 398
events
user defined, 404
exception, 179
Exception
Constructors, 192
Exception Abuse, 179
Exception Handling, 181
when to use, 191
Exceptions
Generating, 193
wrapping, 194
exit code, 43
Explicit initialization, 266
Explicit interface implementation, 351
fields, 155
File class, 172
FileInfo, 167, 179, 220
FileInfo Class, 162
finally, 185
finally block, 185
float, 75
Floor, 173
for loop, 135
foreach loop, 136, 230
with collections, 222
forwarding, 353
function pointer, 367
GAC, 9, 26, 410, 424, 425, 426, 428,
429
garbage collection, 153
Garbage collection, 96
GetElementByTagName, 474
GetEnumerator, 359
GetHashCode, 335
Global Assembly Cache, 424
goto, 139, 141
grep, 123
Index
state, 170
State, 265
static, 42
Static fields, 174, 278
Static methods, 170, 171
StreamReader, 163, 459
StreamWriter, 165
String class, 208
String formatting, 118
StringBuilder, 111
strong name, 425
structs, 83
structure, 237
stuct types
constructors, 243
subclass, 311
switch, 132
target, 383
TextBox, 386
this, 322
Thread class, 368
ThreadStart, 368
throw, 143, 193
TicksPerSecond, 241
TimeSpan, 238, 241
Today, 240
ToString method, 333
Trim, 113
try/catch, 181
TypeCode, 251
Unboxing, 99
unchecked, 186
Unicode, 73, 74
Unix, 123
unsafe, 95
URI, 456
Uri class, 457
URL, 456
user-defined type, 237
ValidationEventHandler, 471
value, 269
Value types, 63
Values, 228
VB, 402, See
VB6, 27, 49, 50, 61, 68, 71, 132, 201,
240, 347, 358, 388, 420
VBScript, 61
virtual, 327
Visual Basic, 2, 12, 19, 28, 49, 61, 62,
63, 68, 69, 120, 136, 148, 149, 151,
166, 208, 240, 247, 388
Web service, 439, 440
Web services, 439, 440, 488
WebMethod attribute, 439
WebRequest class, 458
WebResponse, 458
WebService attribute, 439
while loop, 133
winexe, 383
WSDL, 440
XML, 21, 26, 36, 48, 56, 426, 465, 466,
467, 468, 469, 470, 472, 475, 478, 479,
480, 481, 482, 483, 485
XML documentation, 480
XML namespace, 439, 440, 456
XmlDocument, 469, 472
XmlElement, 473
XmlNode, 474
XmlNodeList, 472, 474
XmlReader, 469
XmlSerializer, 475, 476, 479
XmlTextNode, 474
XmlTextReader, 470
XmlValidatingReader, 470