- Creating Classes
- Creating Objects
- Using Access Modifiers
- Creating Fields and Using Initializers
- Creating Methods
- Creating Properties
- Read-only Properties
- Creating Constructors
- Creating Structs
- Creating Static Members
- Creating Static Fields
- Creating Static Properties
- Creating Destructors and Handling Garbage Collection
- Overloading Methods
- Overloading Operators
- Creating Namespaces
- In Brief
Creating Fields and Using Initializers
The first type of class member we'll take a look at is the field, also called a data member. A field is just a class-level variable, outside any method. If you make your field public, it's accessible using an object of your class; for example, take a look at the Messager class here, which has a field named Message that holds the message that a method named DisplayMessage will display:
class Messager { public string message; public void DisplayMessage() { System.Console.WriteLine(message); } }
Don't Make Fields Public
Although this example shows how to make a field public, it's usually not good programming practice to give external code direct access to the data in your objects. Instead, it's better to use accessor methods or properties, coming up in the next two topics.
Because the message field is public, you can access it using objects of this class. For example, you can assign a string to the message field of a messager object and then call its DisplayMessage method to display that message, as you see in ch03_02.cs, Listing 3.2.
Listing 3.2 Creating Fields (ch03_02.cs)
class ch03_02 { static void Main() { Messager obj = new Messager(); obj.message = "Hello from C#."; obj.DisplayMessage(); } } class Messager { public string message = "Default message."; public void DisplayMessage() { System.Console.WriteLine(message); } }
Here are the results when you run this example. As you can see, we can store data in our new object's public field message, which the DisplayMessage method of that object can use:
C:\>ch03_02 Hello from C#.
You can also initialize fields with intializers, which are just like the initial values you assign to variables. For example, you can use an initializer to assign the string "Default message." to the Message field like this:
class Messager { public string message = "Default message."; public void DisplayMessage() { System.Console.WriteLine(message); } }
If you don't use an initializer, fields are automatically initialized to the values in Table 3.2 for simple values, and to null for reference types.
You can also make fields read-only using the readonly keyword:
public readonly string message = "Default message.";
When a field declaration includes a readonly keyword, assignments to that field can occur only as part of the declaration, with an initializer, or in a constructor in the same class.