Struct Functions


In the last chapter you looked at struct types for storing multiple data elements in one place. Structs are actually capable of a lot more than this. One important extra capability they offer is the ability to contain functions as well as data. This is something that may seem a little strange at first, but it is in fact very useful indeed.

As a simple example, consider the following struct:

 struct customerName { public string firstName, lastName; } 

If you have variables of type customerName, and you want to output a full name to the console, you are forced to build the name from its component parts. You might use the following syntax for a customerName variable called myCustomer, for example:

 customerName myCustomer; myCustomer.firstName = "John"; myCustomer.lastName = "Franklin"; Console.WriteLine("{0} {1}", myCustomer.firstName, myCustomer.lastName); 

By adding functions to structs, you can simplify this by centralizing the processing of common tasks such as this. You can add a suitable function to the struct type as follows:

struct customerName {    public string firstName, lastName;     public string Name () { return firstName + " " + lastName; } } 

This looks much like any other function you've looked at in this chapter, except that you haven't used the static modifier. The reasons for this will become clear later in the book, for now it is enough to know that this keyword isn't required for struct functions. You can use this function as follows:

customerName myCustomer; myCustomer.firstName = "John"; myCustomer.lastName = "Franklin"; Console.WriteLine(myCustomer.Name()); 

This syntax is much simpler, and much easier to understand, than the earlier one.

An important point to note here is that the Name() function has direct access to the firstName and lastName struct members. Within the customerName struct, they can be thought of as global.




Beginning Visual C# 2005
Beginning Visual C#supAND#174;/sup 2005
ISBN: B000N7ETVG
EAN: N/A
Year: 2005
Pages: 278

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net