Time1
Class DeclarationThe public
methods of a class are part of the public services or the public interface that the class provides to its clients.
Methods and properties that modify the values of private
variables should verify that the intended new values are valid.
A class’s methods and properties can throw exceptions to indicate invalid data.
Time1
The actual data representation used within the class is of no concern to the class’s clients. This allows you to change the implementation of the class. Clients could use the same public
methods and properties to get the same results without being aware of this change.
Clients are neither aware of, nor involved in, a class’s implementation. Clients generally care about what the class does but not how the class does it.
Access modifiers public
and private
control access to a class’s variables, methods and properties. A class’s private
variables, methods and properties are not directly accessible to the class’s clients.
If a client attempts to use the private
members of another class, the compiler generates error messages stating that these private
members are not accessible.
this
ReferenceEvery object can access a reference to itself with keyword this
. When a non-static
method is called for a particular object, the method’s body implicitly uses keyword this
to refer to the object’s instance variables, other methods and properties.
If a method contains a local variable with the same name as a field, that method will refer to the local variable rather than the field. However, a non-static
method can use the this
reference to refer to a hidden instance variable explicitly.
Avoid method-parameter names or local-variable names that conflict with field names. This helps prevent subtle, hard-to-locate bugs.
Time
Class Case Study: Overloaded ConstructorsTo overload constructors, provide multiple constructor declarations with different signatures.
Time2
with Overloaded ConstructorsFollowing the constructor header with the constructor initializer :
this
(
args) invokes the matching overloaded constructor in the same class.
Constructor initializers are a popular way to reuse initialization code provided by one of the class’s constructors rather than defining similar code in another constructor’s body.
When one object of a class has a reference to another object of the same class, the first object can access all the second object’s data and methods (including those that are private
).
When implementing a method of a class, use the class’s properties to access the class’s private
data. This simplifies code maintenance and reduces the likelihood of errors.
The ArgumentOutOfRangeException
constructor with three arguments lets you specify the name of the item that’s out of range, the value that was out of range and an error message.
Every class must have at least one constructor. If there are no constructors in a class’s declaration, the compiler creates a default constructor for the class.
The compiler will not create a default constructor for a class that explicitly declares at least one constructor. In this case, if you want to be able to invoke the constructor with no arguments, you must declare a parameterless constructor.
A class can have objects of value types or references to objects of other classes as members. Such a capability is called composition and is sometimes referred to as a has-a relationship.
Every object you create uses various system resources, such as memory. The CLR performs automatic memory management by using a garbage collector to reclaim the memory occupied by objects that are no longer in use.
The destructor is invoked by the garbage collector to perform termination housekeeping on an object before the garbage collector reclaims the object’s memory.
Memory leaks, which are common in other languages like C and C++ (because memory is not automatically reclaimed in those languages), are less likely in C#.
A problem with the garbage collector is that it’s not guaranteed to perform its tasks at a specified time. Therefore, the garbage collector may call the destructor any time after the object becomes eligible for destruction, making it unclear when, or whether, the destructor will be called.
static
Class MembersA static
variable represents classwide information—all objects of the class share the variable.
The scope of a static
variable is the body of its class. A class’s public
static
members can be accessed by qualifying the member name with the class name and the member access (.) operator.
Static class members exist even when no objects of the class exist—they’re available as soon as the class is loaded into memory at execution time.
String objects in C# are immutable—they cannot be modified after they’re created. Therefore, it’s safe to have many references to one string
object.
A method declared static
cannot access non-static
class members directly, because a static
method can be called even when no objects of the class exist. For the same reason, the this
reference cannot be used in a static
method.
readonly
Instance VariablesThe principle of least privilege is fundamental to good software engineering. In the context of an app, the principle states that code should be granted only the amount of privilege and access needed to accomplish its designated task, but no more.
Any attempt to modify a readonly
instance variable after its object is constructed is an error.
Although readonly
instance variables can be initialized when they’re declared, this is not required. A readonly
variable can be initialized by each of the class’s constructors.
Members that are declared as const
must be assigned values at compile time. Constant members with values that cannot be determined at compile time must be declared with keyword readonly
, so they can be initialized at execution time.
When an auto-implemented property has only a get
accessor, the property can be used only to read the value, so the compiler implicitly declares the corresponding private instance variable as readonly
.
The Class View displays the fields, methods and properties for all classes in a project. The view follows a hierarchical structure, positioning the project name as the root and including a series of nodes that represent the classes, fields, methods and properties in the project.
The Object Browser lists all classes of the Framework Class Library. The Object Browser can be a quick mechanism to learn about a class or method of a class.
Object initializers allow you to create an object and initialize its public
properties (and public
instance variables, if any) in the same statement.
An object-initializer list is a comma-separated list in curly braces ({}
) of properties (and public
instance variables, if any) and their values.
Each property and instance variable name can appear only once in the object-initializer list.
An object initializer first calls the class’s constructor, then sets in the order in which they appear the value of each property and variable specified in the object-initializer list.
struct
Method-call notation is cumbersome for certain kinds of classes, especially mathematical classes. Sometimes, it’s convenient to use C#’s built-in operators to specify object manipulations.
struct
You can define your own value types as struct
s.
C#’s simple types like int
and double
are actually aliases for struct
types.
Microsoft recommends using classes for most new types, but recommends a struct
if: the type represents a single value and the size of an object is 16 bytes or smaller.
ComplexNumber
Keyword operator
, followed by an operator, indicates that a method overloads the specified operator. Methods that overload binary operators must be declared static
and must take two arguments. The first argument is the left operand, and the second is the right operand.
Overload operators to perform the same function or similar functions on class objects as the operators perform on objects of simple types. Avoid nonintuitive use of operators.
Time
Class Case Study: Extension MethodsExtension methods add functionality to a type without modifying the types’s source code.
LINQ capabilities are implemented as extension methods.
Preceding an object parameter that’s the first parameter in the method header with the this
keyword indicates that the method extends an existing type. The compiler uses this information to add code into the compiled program that enables extension methods to work with existing types.
The type of an extension method’s first parameter specifies the type that you’re extending.
Extension methods must be defined as static
methods in a static
class.
The compiler implicitly passes the object that’s used to call the method as the extension method’s first argument. This allows you to call an extension method as if it were an instance method of the extended class.
IntelliSense displays extension methods with the extended class’s instance methods and identifies them with a distinct icon.
Cascaded method calls are called from left to right.
An extension method’s fully qualified name is the name of the class in which the extension method is defined, followed by the name of the method and its argument list. When using the fully qualified method name, you must specify an argument for first parameter.
If the type being extended defines an instance method with the same name as your extension method and a compatible signature, the instance method shadows the extension method.