Creating Objects

To create an object, also called an instance, of a class, you use the new keyword. We've seen how this process works; you can see how we create a new object of the Calculator class in ch03_01.cs, Listing 3.1, and use that object's Addem method to add 2 and 3. Note the parentheses after Calculator in the statement Calculator obj = new Calculator();. These parentheses are necessary when you use the new keyword. They let you pass data to a class's constructor, the special method that lets you initialize the data in a class. We'll go into depth about constructors later in this chapter.

Listing 3.1. Creating a New Class (ch03_01.cs)
class ch03_01
{
  static void Main()
  {
    Calculator obj = new Calculator();
					 System.Console.WriteLine("2 ...

Get Microsoft® Visual C#® .NET 2003 Kick Start now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.