Each class you create becomes a new type you can use to create objects, so C# is an extensible programming language.
Account
ClassClasses cannot execute by themselves.
A class containing a method that tests another class’s capabilities is referred to as a driver class.
new
and ConstructorsTypically, you cannot call a method of a class until you create an object of that class.
An object-creation expression uses the new
operator to create an object.
Account
’s GetName
MethodTo call a method for a specific object, you specify the object’s name, followed by the member-access operator (.
), then the method name and a set of parentheses. Empty parentheses indicate that a method does not require any additional information to perform its task.
When a method is called, the app transfers execution from the method call to the method’s declaration, the method performs its task, then control returns to the point of the method call.
Console
method ReadLine
reads characters until it encounters the newline, then returns a string
containing the characters up to, but not including, the newline, which is discarded.
Account
’s SetName
MethodA method call can supply arguments that help the method perform its task. You place the arguments in the method call’s parentheses.
Account
Class with an Instance Variable and Set and Get MethodsThe fact that you can create and manipulate an object of a class without knowing the class’s implementation details is called abstraction.
Account
Class DeclarationA class’s instance variables maintain data for each object of the class.
class
and the Class BodyEvery class declaration contains the keyword class
followed immediately by the class’s name.
Each class declaration is typically stored in a file having the same name as the class and ending with the .cs
filename extension.
The class’s body is enclosed in a pair of braces.
Class, property, method and variable names are all identifiers and by convention all use the camel-case naming scheme. Class, property and method names begin with an initial uppercase letter and variable names begin with an initial lowercase letter.
name
of Type string
Each object has its own copy of the class’s instance variables.
Instance variables exist before an app calls methods or accesses properties on an object, while the methods and properties are executing, and after the methods and properties complete execution.
Instance variables are declared inside a class declaration but outside the bodies of the class’s methods and properties.
Clients of a class—that is, any other code that calls the class’s methods (or accesses its properties)—cannot access the class’s private
instance variables. However, clients can access a class’s public
methods (and properties).
Every instance variable has a default initial value—a value provided by C# when you do not specify the instance variable’s initial value.
Instance variables are not required to be explicitly initialized before they’re used in a program— unless they must be initialized to values other than their default values.
The default value for an instance variable of type string
is null
.
When you display the value of a string
variable that contains the value null
, no text is displayed on the screen.
SetName
MethodThe return type void
indicates that a method does not return any information to its caller.
A method can require one or more parameters that represent the data it needs to perform its task.
Parameters are declared in a parameter list located in the required parentheses following the method’s name.
Each parameter must specify a type followed by a parameter name. When there are multiple parameters, each is separated from the next by a comma.
Each argument value in a method call’s parentheses is copied into the method declaration’s corresponding parameter.
The number and order of arguments in a method call must match the number and order of parameters in the method declaration’s parameter list.
Every method body is delimited by an opening left brace and a closing right brace. Within the braces are one or more statements that perform the method’s task(s).
Variables declared in a particular method’s body are local variables which can be used only in that method. A method’s parameters also are local variables of that method.
GetName
MethodWhen a method with a return type other than void
is called and completes its task, it must return a result to its caller via a return
statement.
private
and public
The keyword private
is an access modifier.
A private
instance variable is accessible only to methods (and other members, like properties) of the instance variable’s class. This is known as information hiding.
Most instance variables are declared private
.
Methods (and other class members) that are declared public
can be used by methods (and other members) of the class in which they’re declared, by the class’s clients.
By default, class members are private
, unless you specify otherwise with access modifiers.
Account
UML Class DiagramUML class diagrams summarize a class’s attributes and operations.
UML diagrams help systems designers specify systems in a concise, graphical, programming-language-independent manner, before programmers implement the systems in specific programming languages.
In the UML, each class is modeled in a class diagram as a rectangle with three compartments.
The top compartment contains the class name centered horizontally in boldface type.
The middle compartment contains the class’s attributes.
A minus sign (–) access modifier an the attribute name indicates that the attribute is private
.
Following an attribute name are a colon and the attribute type.
The bottom compartment contains the class’s operations.
The UML models operations by listing the operation name preceded by an access modifier.
A plus sign (+
) indicates a public operation.
The UML indicates the return type of an operation by placing a colon and the return type after the parentheses following the operation name.
The UML models a parameter by listing the parameter name, followed by a colon and the parameter type in the parentheses after the operation name.
You can open each class in the Visual Studio editor by double clicking the file’s name in the Solution Explorer window.
When you select Build > Build Solution in Visual Studio, the IDE compiles all the files in the project to create the executable app.
Set and Get methods can validate attempts to modify private
data and control how that data is presented to the caller, respectively.
Account
Class with a Property Rather Than Set and Get MethodsA property contains a set
accessor for storing a value into a variable and a get
accessor for getting the value of a variable.
AccountTest
Using Account’s Name
PropertyTo access a property to get its value, specify the object’s name, followed by the member-access operator (.
) and the property’s name—this implicitly executes the property’s get
accessor, unless the expression is on the left side of an assignment.
Accessing a property on the left of an assignment implicitly executes the property’s set
accessor.
Account
Class with an Instance Variable and a PropertyA property declaration specifies the property’s access specifier, type, name and body.
By convention, a property’s identifier is the capitalized identifier of the instance variable that it manipulates.
A get
accessor begins with the contextual keyword get
followed by a body, which contains a return
statement that returns the value of a corresponding instance variable.
The property notation allows the client to think of the property as the underlying data.
A set
accessor begins with the contextual keyword set
followed by its body.
A set
accessor’s contextual keyword value
is implicitly declared and initialized for you with the value that the client code assigns to the property.
Account
UML Class Diagram with a PropertyC# properties are modeled in the UML as attributes. A public property is indicated by the plus (+) sign followed by the word “property” in guillemets («
and »
), then the property’s name, a colon and the property’s type.
Using descriptive words in guillemets (called stereotypes in the UML) helps distinguish properties from other attributes and operations.
A class diagram helps you design a class, so it’s not required to show every implementation detail.
Since an instance variable that’s manipulated by a property is really an implementation detail of that property, a class diagram does not show a property’s corresponding instance variable.
Similarly, a property’s get
and set
accessors are implementation details, so they’re not listed in a UML diagram.
For properties in which the get
accessor simply returns an instance variable’s value and a set
accessor simply assigns a value to the instance variable, C# provides auto-implemented properties.
With an auto-implemented property, the C# compiler creates a hidden private
instance variable, and the get
and set
accessors for getting and setting that instance variable.
Account
Class: Initializing Objects with ConstructorsEach class you declare optionally can provide a constructor with parameters that can be used to initialize an object when it’s created.
C# requires a constructor call for every object that’s created, so this is the ideal point to initialize an object’s instance variables.
Account
Constructor for Custom Object InitializationA constructor must have the same name as its class.
An important difference between constructors and methods is that constructors cannot specify a return type (not even void
).
Normally, constructors are declared public
so they can be used by the class’s client code to initialize objects of the class.
AccountTest
: Initializing Account
Objects When They’re CreatedCreating an object with new
implicitly calls the class’s constructor to initialize the object.
In any class that does not explicitly declare a constructor, the compiler provides a public
default constructor with no parameters.
When a class has only the default constructor, the class’s instance variables are initialized to their default values—0 for numeric simple types, false
for simple type bool
and null
for all other types.
If you declare one or more constructors for a class, the compiler will not create a default constructor.
The UML models constructors as operations in the third compartment of a class diagram. To distinguish a constructor from the class’s other operations, the UML requires that the word “constructor” be enclosed in guillemets (« and ») and placed before the constructor’s name.
It’s customary to list constructors before other operations in the third compartment.
Account
Class with a Balance; Processing Monetary AmountsType decimal
is designed to precisely represent numbers with decimal points, such as monetary amounts.
Account
Class with a decimal balance
Instance VariableA decimal
instance variable is initialized to zero by default.
A property’s set accessor can performs validation (also known as validity checking).
The letter m
appended to a numeric literal indicates the number is a decimal
literal.
By default, the get
and set
accessors of a property have the same access as the property.
get
and set
accessors can have different access modifiers. One of the accessors must implicitly have the same access as the property and the other must be declared with more restrictive access.
A property’s private set
accessor may be used only by the property’s class, not by the class’s clients.
AccountTest
Class That Creates and Uses Account
ObjectsYou can specify formatting in a C# 6 string
interpolation expression by following the value in the braces with a colon and a format specifier.
The format specifier C
formats a numeric value as currency (C
is for currency)—typically with two digits to the right of the decimal point.
The Windows culture settings on the user’s machine determine the format for displaying currency amounts, such as the commas vs. periods for separating thousands, millions, etc.
Unlike instance variables, local variables are not initialized by default.
Type decimal
’s Parse
method converts a string
to a decimal
value.