Cover | Table of Contents | Colophon
System.Object.
The CTS supports the general concept of classes, interfaces, and
delegates (which support callbacks).
class Hello
{
static void Main( )
{
// Use the system console object
System.Console.WriteLine("Hello World");
}
}
Hello class. To define a C#
type, you declare it as a class using the class
keyword, give it a name—in this case,
Hello—and then define its properties and
behaviors. The
property and behavior definitions of a
C# class must be enclosed by open and closed braces
(Hello class. To define a C#
type, you declare it as a class using the class
keyword, give it a name—in this case,
Hello—and then define its properties and
behaviors. The
property and behavior definitions of a
C# class must be enclosed by open and closed braces
({}
).WriteLine( ) or
int,
bool, etc.) versus user-defined types (types you
create as classes and interfaces). The chapter also covers
programming fundamentals such as how to create and use variables and
constants. It then goes on to introduce enumerations, strings,
identifiers, expressions, and statements.if,
switch, while,
do...while, for, and
foreach statements. Also discussed are operators,
including the assignment, logical, relational, and mathematical
operators. This is followed by an introduction to namespaces and a
short tutorial on the C# precompiler.int
indicates an object of 4 bytes) and its capabilities (e.g., buttons
can be drawn, pressed, and so forth).int
indicates an object of 4 bytes) and its capabilities (e.g., buttons
can be drawn, pressed, and so forth).& operator). Also, pointers
aren't normally used (but see Chapter 22 for the exception to this rule).x and y are variables.
Variables can have values assigned to them, and those values can be
changed programmatically.#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace InitializingVariables
{
class Values
{
static void Main( )
{
int myInt = 7;
System.Console.WriteLine("Initialized, myInt: {0}",
myInt);
myInt = 5;
System.Console.WriteLine("After assignment, myInt: {0}",
myInt);
}
}
}
Output:
Initialized, myInt: 7
After assignment, myInt: 5myVariable = 57;
57.57 to the variable myVariable.
The assignment operator (=)
doesn't test equality; rather it causes whatever is
on the right side (57) to be assigned to whatever
is on the left side (myVariable). All the C#
operators (including assignment and equality) are discussed later in
this chapter (see "Operators").myVariable
=
57 is an expression that evaluates to
57, it can be used as part of another assignment
operator, such as:mySecondVariable = myVariable = 57;
57 is assigned to the variable
myVariable. The value of that assignment
(57) is then assigned to the second variable,
mySecondVariable. Thus, the value
57 is assigned to both variables. You can
therefore initialize any number of variables to the same value with
one statement:a = b = c = d = e = 20;
myVariable = 5;
myVariable = 5;
Console.WriteLine("Hello World")
int x = 5;
int x=5;
intx=5;
int and the variable name
x is not extra, and is
required. This is not surprising: the whitespace allows the compiler
to parse the keyword int rather than some unknown
term intx. You are free to add as much or as
little whitespace between int and
x as you care to, but there must be at least one
whitespace character (typically a space or tab).;).
For example:int x; // a statement x = 23; // another statement int y = x; // yet another statement
for
, while,
do, in, and
foreach. Iteration is discussed later in this
chapter. For now, let's consider some of the more
basic methods of conditional and unconditional branching.#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace CallingAMethod
{
class CallingAMethod
{
static void Main( )
{
Console.WriteLine("In Main! Calling SomeMethod( )...");
SomeMethod( );
Console.WriteLine("Back in Main( ).");
}
static void SomeMethod( )
{
Console.WriteLine("Greetings from SomeMethod!");
}
}
}
Output:
In Main! Calling SomeMethod( )...
Greetings from SomeMethod!
Back in Main( ).int) support a number of operators such as
assignment, increment, and so forth.+), subtraction (-),
multiplication (*), and division
(/) operators work as you might expect, with the
possible exception of
integer division.4
(17/4
=
4,
with a remainder of 1). C# provides a special
operator (modulus, %, which is described in the
next section) to retrieve the remainder.%). For
example, the statement 17%4 returns
1 (the remainder after integer division).#).
These directives allow you to define identifiers and then test for
their existence.#define
DEBUG defines a preprocessor identifier,
DEBUG. Although other preprocessor directives can
come anywhere in your code, identifiers must be defined before any
other code, including using statements.DEBUG has been defined with
the #if
statement. Thus, you can write:#define DEBUG //... some normal code - not affected by preprocessor #if DEBUG // code to include if debugging #else // code to include if not debugging #endif //... some normal code - not affected by preprocessor
#define
statement and records the identifier DEBUG. The
preprocessor skips over your normal C# code and then finds the
#if
-
#else
-
#endif block.#if statement tests for the identifier
DEBUG, which does exist, and so the code between
int, long, and
char. The heart and soul of C#, however, is the
ability to create new, complex, programmer-defined types that map
cleanly to the objects that make up the problem you are trying to
solve.Dog class describes what dogs are like: they
have weight, height, eye color, hair color, disposition, and so
forth. They also have actions they can take, such as eat, walk, bark,
and sleep. A particular dog (such as my dog Milo) has a specific
weight (62 pounds), height (22 inches), eye color (black), hair color
(yellow), disposition (angelic), and so forth. He is capable of all
the actions of any dog (though if you knew him you might imagine that
eating is the only method he implements).class keyword. The complete syntax is as follows:[attributes] [access-modifiers] class identifier [:base-class [,interface(s)]] {class-body}
public as an access
modifier.) The identifier is the name of the class
that you provide. The optional base-class is
discussed in Chapter 5. The member definitions
that make up the class-body are enclosed by open
and closed curly braces ({}).int and a variable of type
int. Thus, while you would write:int myInteger = 5;
int = 5;
int).int, char, etc.) are value
types, and are created on the stack. Objects, however, are reference
types, and are created on the heap, using the keyword
new
, as in the following:Time t = new Time();
t doesn't actually contain the
value for the Time object; it contains the address
of that (unnamed) object that is created on the heap.
t itself is just a reference to that object.Dim
and New on
the same line, in C# this penalty has been removed. Thus, in C# there
is no drawback to using the new keyword when
declaring an object variable.Time object looks as though it is invoking a
method:Time t = new Time();
type.Time class of Example 4-1
doesn't define a constructor. If a constructor is
not declared, the compiler provides one for you. The default
constructor creates the object but takes no other action.Button and have instantiated objects of that
class named btnUpdate and
btnDelete. Suppose as well
that the Button class has a static
method
SomeMethod(). To access the static method, you
write:Button.SomeMethod();
btnUpdate.SomeMethod( );
static keyword in C# with the
Static keyword in VB6 and VB.NET. In VB, the
Static keyword declares a variable that is
available only to the method it was declared in. In other words, the
Static variable is not shared among different
objects of its class (i.e., each Static variable
instance has its own value). However, this variable exists for the
life of the program, which allows its value to persist from one
method call to another.static keyword indicates a class
member. In VB, the equivalent keyword is Shared.~MyClass(){}
Finalize( ) method that chains up to its base
class. Thus, when you write:ref
parameter modifier for passing value
objects into a method by reference, and the
out
modifier for those cases in which you
want to pass in a ref variable without first
initializing it. C# also supports the params
modifier, which allows a method to accept a variable number of
parameters. The params keyword is discussed in
Chapter 9.Time class
and add a GetTime() method, which returns the
hour, minutes, and seconds.int (integer).
Instead, use reference parameters.#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace ReturningValuesInParams
{
public class Time
{
// private member variables
private int Year;
private int Month;
private int Date;
private int Hour;
private int Minute;
private int Second;
// public accessor methods
public void DisplayCurrentTime( )
{
System.DateTime object. It would be convenient to be
able to set new Time objects to an arbitrary time
by passing in year, month, date, hour, minute, and second values. It
would be even more convenient if some clients could use one
constructor, and other clients could use the other constructor.
Function overloading provides for exactly these contingencies.void myMethod(int p1); void myMethod(int p1, int p2); void myMethod(int p1, string s1);
Time
class with two constructors: one that takes a
DateTime object, and the other that takes six
integers.#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace OverloadedConstructor
{
public class Time
{
// private member variables
private int Year;
private int Month;
private int Date;
private int Hour;
private int Minute;
private int Second;
// public accessor methods
public void DisplayCurrentTime( )
{
System.Console.WriteLine( "{0}/{1}/{2} {3}:{4}:{5}",
Month, Date, Year, Hour, Minute, Second );
}
// constructors
public Time class is first created, the
Hour value might be stored as a member variable.
When the class is redesigned, the Hour value might
be computed or retrieved from a database. If the client had direct
access to the original Hour member variable, the
change to computing the value would break the client. By decoupling
and forcing the client to go through a method (or property), the
Time class can change how it manages its internal
state without breaking client code.#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace UsingAProperty
{
public class Time
{
// private member variables
private int year;
private int month;
private int date;
private int hour;
private int minute;
private int second;
// public accessor methods
public void DisplayCurrentTime( )
{
System.Console.WriteLine(
"Time\t: {0}/{1}/{2} {3}:{4}:{5}",
month, date, year, hour, minute, second );
}
// constructors
public Time( System.DateTimeTime class
that is responsible for providing public static values representing
the current time and date. Example 4-12 illustrates a
simple approach to this problem.#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace StaticPublicConstants
{
public class RightNow
{
// public member variables
public static int Year;
public static int Month;
public static int Date;
public static int Hour;
public static int Minute;
public static int Second;
static RightNow( )
{
System.DateTime dt = System.DateTime.Now;
Year = dt.Year;
Month = dt.Month;
Date = dt.Day;
Hour = dt.Hour;
Minute = dt.Minute;
Second = dt.Second;
}
}
public class Tester
{
static void Main( )
{
System.Console.WriteLine( "This year: {0}",
RightNow.Year.ToString( ) );
RightNow.Year = 2006;
System.Console.WriteLine( "This year: {0}",
RightNow.Year.ToString( ) );
}
}
}
Output:
This year: 2005
This year: 2006
RightNow.Year value can be changed, for example,
to 2006. This is clearly not what
we'd like.readonly for exactly this purpose. If you
change the class member variable declarations as follows:public static readonly int Year; public static readonly int Month; public static readonly int Date; public static readonly int Hour; public static readonly int Minute; public static readonly int Second;