Microsoft Visual C#.NET 2003 Kick Start
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); } }
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. |