PDA

Click to See Complete Forum and Search --> : Still confused about structs


Nightm@re
Dec 3rd, 2003, 02:51 AM
I just started programming in C# about three days ago. I'm still fairly confused on when I should be using structs vs. classes.

Thus far, I know that structs are value types and performance can be increased by utilizing them.

I also know that if I want a parameterless constructor for any reason classes are the only way to go. As well - classes can have destructors while structs can not.

Half the time I just can't decide on whether to use the struct or class keyword. Should I simply use structs if possible? And if so...does this mean many programmers overutilize classes?

Memnoch1207
Dec 3rd, 2003, 09:01 AM
Rule of thumb...classes can be inherited (derived) from...Structs can't. You create an instance of a class which gets stored in memory (a reference type, created on the heap). A struct is a value type and created on the stack (which allows for faster retrieval of the information).

say you wanted to create something about employees in you company. you could do it with a class.

Base Class Employee

Then you could create another class called SalariedEmployee which inherits the base functionality of the EmployeeClass.
Then you could create another class called HourlyEmployee.
See where I am going with this???

or you could just create a structure to do this for you.

public struct Employee
{
string firstName;
string lastName;
boolean salaried;
etc...

}


Classes are generally used to implement a piece of business logic, rather than to support data related primitive like objects.

Pirate
Dec 4th, 2003, 10:04 PM
Simply Struct is variables grouped under one name .

wossname
Dec 5th, 2003, 03:02 AM
Nightm@re, if you have any VB6 experience, a struct is more or less the same as a user defined Type (UDT).

Nightm@re
Dec 5th, 2003, 08:29 AM
Thanx for all the responses :).

After reading all your replys and programming a bit more the differences between the two have become much more apparent.