Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

why use struct

Status
Not open for further replies.

Jefhandle

Technical User
Mar 9, 2005
69
DE
i'm new in c sharp and i read about struct,which is more like a class. But i still dont understan realy, why i should struct?what is advantage? i read that that structs cannot be abstract and do not support implementation inheritance. i could unnderstand this and than thay said the important difference with a class is that structs are value types, while classes are reference types?what is the big advantage of this?
thanks
 
Not much, I think the only benifit of value types is that they are slightly more efficient in terms of speed. Value types are store in the stack, while reference types are store in the heap. So, value types access the values directly from the stack. On the other hand reference types are store on the heap and needs a pointer to point to the memory area in the heap where the object is stored. There is a slight penalty from going from the pointer to the memory area and dereferencing it.

That is what I understand of it. You probably wouldn't see any benifits unless you are working with a large dataset. Hopes that helps you.
 
I'm not sure if this is true about C#, but in C++ a struct was traditionally used to store data only (no functions). i.e. all data is public. Although a struct could still store member functions like a class if you really wanted to.
 
I like using structs to build a collection of objects for a datasource for a combo box, list box, etc. It's a bit more lightweight than a class. The difference may not be huge but if you are building a large collection, it might pay off.

Another difference between a class and a struct is that a struct cannot have a parameter-less constructor, while a class obviously can. You can't use a destructor on a struct.

A struct acts as a sealed class in the sense that you can't inherit from it.

Below is an article that explains structs in greater detail.





The wisest people are those who are smart enough to realize they don't know it all.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top