Struct or Class

M

Mantorok

I've always followed a particular standard when considering structs, I
mainly use a struct when a class isn't necessary (ie no requirement for
multiple references).

What is the recommendation when considering structs? What matters and does
it "really" make a big difference?

Thanks
Kev
 
A

Andy

It makes a difference; as you probably know, you must fully initial a
struct by the time the constructor ends, so every field must have a
value. Also, I believe structs are allocated on the stack instead of
the heap. I think structs are 'faster' to use than a class, because
they are not as heavyweight as a class would be. All structs are
implicitly 'sealed' so you can't inherit from them.

Here's a good list: http://www.jaggersoft.com/pubs/StructsVsClasses.htm
 
J

james.curran

A struct is a value type. Therefore, it should be used whenever the
object it represents acts like a value, that is, if two separate
objects with the value are the same as being the same object.

int a = 5;
int b = a;
a = 6;
// but b remains equal to 5;

Person d = new Person("John Smith");
Person e = d;
d.LastName = "Jones";

Now d = "John Jones". Now, in your case, should e = "John Jones"
(reference type, class), or "John Smith" (value type, struct) ?
 
B

Bruce Wood

James nailed it.

This topic comes up here once every few weeks. You can read lots of
back-and-forth about when to use struct. Just search the archives of
this group for "struct vs class" or something like that, and you'll
find lots of spirited discussion.
 
B

Bruce Wood

Alvin said:
A struct is a simplified class...(waiting for the fire and brimstone :-(

"Your mother was a hamster, and your father smelt of elderberries!"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top