Chapter 3. Creating Types in C#
In this chapter, we will delve into types and type members.
Classes
A class is the most common kind of reference type. The simplest possible class declaration is as follows:
class YourClassName
{
}A more complex class optionally has the following:
Preceding the keyword
| Attributes and
class modifiers. The non-nested class
modifiers are |
Following | Generic type parameters, a base class, and interfaces |
Within the braces | Class members (these are methods, properties, indexers, events, fields, constructors, operator functions, nested types, and a finalizer) |
This chapter covers all of these constructs except attributes,
operator functions, and the unsafe
keyword, which are covered in Chapter 4. The
following sections will enumerate each of the class members.
Fields
A field is a variable that is a member of a class or struct. For example:
class Octopus
{
string name;
public int Age = 10;
}Fields allow the following modifiers:
Static modifier |
|
Access modifiers |
|
Inheritance modifier |
|
Unsafe code modifier |
|
Read-only modifier |
|
Threading modifier |
|
The readonly modifier
The readonly modifier prevents a field from being
modified after construction. A read-only field can be assigned only
in its declaration or within the enclosing type’s
constructor.
Field initialization
Field initialization is optional. An uninitialized field has a default value ( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access