Chapter 3: Learning Just Enough C# and VB.NET: Types and Members

69

{

public class Employee

{

public string FirstName;

}

}

VB:

Public Class Employee

Public Dim FirstName As String

End Class

The C# Employee class is nearly the same as the Program class that you created in the preceding chapter, except that the class name here is Employee. In VB, you’ve only created a module before, and the Employee class is your first class for this book. You can add members to a class, which could be events, fields, methods, and properties. Listing 3-1 shows an example of a field, FirstName, and you’ll learn about events, methods, and properties in later sections of this chapter. A field is a variable in a class that holds information specific to that class.

Listing 3-2 shows how to instantiate an object of type Employee, which is your new custom type, and use it. You would put this code inside of Main or another method. You’ll learn more about methods in the later section “Writing Methods.”

Listing 3-2 Code that uses a class

C#:

Employee emp = new Employee(); emp.FirstName = "Joe";

VB:

Dim emp As New Employee emp.FirstName = "Joe"

In Listing 3-2, you can see that emp is a variable declared as type Employee. The C# new Employee() or VB New Employee clause creates a new instance of Employee, and you can see that this new instance is being assigned to emp. With that new instance, via the emp variable, you can access the Employee object, including its instance members. In Listing 3-2, the FirstName field of that particular instance of Employee is assigned a string value of "Joe". Here you see that an object can contain data.

Page 92
Image 92
Microsoft 9GD00001 manual Learning Just Enough C# and VB.NET Types and Members, Listing 3-2 Code that uses a class