Monday, May 21, 2007

Struct Functions

Structs are used for storing multiple data elements in one place. Also it has the ability to contain functions as well as data.
Struct Example:
Struct CustomerName
{
public string firstName, lastName;
}
You can use the struct in your code as follows:
CustomerName myCustomer;
myCustomer.firstName = “John”;
myCustomer.lastName = “Franklin”;
Console.WriteLine(“{0} {1}”, myCustomer.firstName, myCustomer.lastName);

Adding Functions to Structs:
By adding functions to structs, you can simplify this by centralizing the processing of common tasks such as follows:
Struct CustomerName
{
public string firstName, lastName;

public string Name()
{
return firstName + “” + lastName;
}
}
Now you can use the struct in your code as follows:
CustomerName myCustomer;
myCustomer.firstName = “John”;
myCustomer.lastName = “Franklin”;
Console.WriteLine( myCustomer.Name());

What is the difference between a struct and a class in C#?
The list of similarities between classes and structs is as follows:
· Longstructs can implement interfaces and can have the same kinds of members as classes.
Structs differ from classes in several important ways; however,
· structs are value types rather than reference types, and inheritance is not supported for structs.
· Struct values are stored on the stack or in-line.
· Careful programmers can sometimes enhance performance through judicious use of structs.
For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.

No comments: