![]() |
Using a Class |
To use a class in a program, you can declare a variable for it. You start with the name of the class, followed by a name for the variable, followed by a semi-colon. Here is an example: using System; class House { char TypeOfHome; int NumberOfBedrooms; double NumberOfBathrooms; byte Stories; int YearBuilt; double Value; } public class Exercise { static int Main() { House home; return 0; } } You can declare two or more class variables with one type. Here are examples: using System; class House { char TypeOfHome; int NumberOfBedrooms; double NumberOfBathrooms; byte Stories; int YearBuilt; double Value; } public class Exercise { static int Main() { House home; House singleFamily, townhouse; return 0; } } After declaring a variable of a class, before using that variable, you must allocate memory for it. This is done using the new operator assigned to the variable and followed by the name of the class, its parentheses, and a semi-colon. Here is an example: using System; class House { char TypeOfHome; int NumberOfBedrooms; double NumberOfBathrooms; byte Stories; int YearBuilt; double Value; } public class Exercise { static int Main() { House home; home = new House(); return 0; } } You can also allocate memory when declaring the variable.
class House { public char TypeOfHome; public int NumberOfBedrooms; private double NumberOfBathrooms; public byte Stories; private int YearBuilt; public double Value; } When a member is declared private, you cannot access it outside of its class. When an access level is not set for a class, all of its members are private by default.
There are various techniques used to initialize an object. To initialize a member of an object, access it and assign it an appropriate value. Here is an example: using System; class House { public char TypeOfHome; public int NumberOfBedrooms; public double NumberOfBathrooms; public byte Stories; public int YearBuilt; public double Value; } public class Exercise { static int Main() { House home; home = new House(); home.NumberOfBathrooms = 2.5; home.Stories = 3; home.Value = 524885; home.YearBuilt = 1962; home.TypeOfHome = 'S'; home.NumberOfBedrooms = 5; Console.Write("Type of Home: "); Console.WriteLine(home.TypeOfHome); Console.Write("Number of Bedrooms: "); Console.WriteLine(home.NumberOfBedrooms); Console.Write("Number of Bathrooms: "); Console.WriteLine(home.NumberOfBathrooms); Console.Write("Number of Stories: "); Console.WriteLine(home.Stories); Console.Write("Year Built: "); Console.WriteLine(home.YearBuilt); Console.Write("Monetary Value: "); Console.WriteLine(home.Value); return 0; } } This would produce: Type of Home: S Number of Bedrooms: 5 Number of Bathrooms: 2.5 Number of Stories: 3 Year Built: 1962 Monetary Value: 524885 Press any key to continue . . . Notice that we initialized the members in any order of our choice. |
|
||
Previous | Copyright © 2006-2016, FunctionX, Inc. | |
|