|
|
|
Now that you're used to the way objects behave, it's time to inform you that, as usual in programming, you have an alternative. There is a construct in C# that shares many of the same abilities as classes, but is also fundamentally different. That construct is called... well, a "struct". struct EmployeeInfo { public string Name; public double Salary; public double GetAnnualSalary() { // Hourly Salary * Hours in Week * Weeks in Year return Salary * 40 * 52; } } A struct is kind of like a "dumb" class. It can have public and private data, as well as static and non-static data. It can also contain methods and properties. Structs aren't intended to be as flexible or powerful as classes; they're mainly used to group various pieces of information into one package. Classes are capable of much more than that. Structs also differ from classes in that they are passed around like ordinary variables. You need the "ref" keyword for a method to be able to change the original struct. Likewise, assigning one struct to another will simply copy its data. It will not result in two structs that actually reference the same thing. Combine that with the fact that they are lightweight and take up less memory, and you will see why structs are so handy when data grouping is your only concern. Two well-known examples of structs in the .NET framework are Point (which groups an X and Y value together) and Size (which groups a Width and Height value together). In both cases, the struct is used to bundle two pieces of related information into one package. If you want to group a number of related variables together, or if you intend to create a LOT of instances (say, 1000 or more), structs are quite useful. They may also be helpful in reducing the number of parameters you need in a method, if you're sending a lot of arguments that are really part of the same thing. Classes are still more powerful and flexible, however, so they're typically used more often. Whoo, that was a quick lesson, wasn't it? Review the code sample to see how a struct might be used. using System; namespace E_Structs { class Class1 { [STAThread] static void Main(string[] args) { EmployeeInfo info = new EmployeeInfo(); info.Name = "Bob"; info.Salary = 20.0; Console.WriteLine("EmployeeInfo: Name = {0}, Salary = {1}, AnnualSalary = {2}", info.Name, info.Salary, info.GetAnnualSalary()); // Normal behavior: original object is unchanged Console.WriteLine("Employee's name before method call: " + info.Name); UseEmployeeInfo(info); Console.WriteLine("Employee's name after method call: " + info.Name); } static void UseEmployeeInfo(EmployeeInfo info) { info.Name = "No one will see this; I'm just a copy!"; } } struct EmployeeInfo { public string Name; public double Salary; public double GetAnnualSalary() { // Hourly Salary * Hours in Week * Weeks in Year return Salary * 40 * 52; } } } |
|