newbie: Structure and Class?

  • Thread starter Thread starter Russell
  • Start date Start date
R

Russell

Can you have a structure that contains a collection of objects created by a
class?

Example:
Structure - Bag of Marbles: BagOfMarbles.Count(),
BagOfMarbles.Marble(1).Color, etc.
Class - Marble: Marble().Color, Marble().Description

Now the twist -
I want BagOfMarbles.CountOfBlueMarbles()

Now the structure will need to access all objects of Marble, check the
color and see if it is blue, if so then count++.

The BagOfMarbles is not an object. I will never have 2 bags of marbles.
It will be a container that allows me to access to individual marbles and
the ability to compare marble(1) versus marble(2), plus the ability to sort
marbles.

I will control access to the marbles through the marble structure. One note,
I may not need marbles to be an class. Marbles will not change color in the
bag. All the properties of Marbles will be static and loaded at run time via
a datasource.

Thanks.
 
Russel,

Is there any specific reason that you want to use a structure (by instance
an API that needs this structure as you describe it). Otherwise, why not
just make it complete classes?

Just my thought reading your message,

Cor
 
Again; why struct? I would expect reference-type semantics here so that
I can pass it (the bag) to e.g. a function without it getting cloned...
I will never have 2 bags of marbles
want BagOfMarbles.CountOfBlueMarbles()

You almost /certainly/ will if you use struct ;-p
There is no issue with a member function like CountOfBlueMarbles()
(although CountByColor(Color color) would be more reusable). If you
really mean ONE bag of marbles, perhaps you should look at the
singleton pattern.
I may not need marbles to be an class. Marbles will not change color in the
bag. All the properties of Marbles will be static and loaded at run time via
a datasource.

Assuming you mean "readonly" or "immutable" (since "static" kinda has
reserved meaning), then I'm not sure that this would be the determining
factor between struct and class (although it is preferable to (as in
your case) only create immutable structs). This still feels like an
object to me - if memory usage is your concern, then this may be
premature optimisation - i.e. you're worrying too early... and if you
already know that you have 30gazillion marbles (hence the memory
concerns), then container classes aren't necessarily the way to go
anyway...

Marc
 
Russell said:
Can you have a structure that contains a collection of objects created by a
class?

You can - but like the other responders, I see no reason to in this
case.

Given your message, you appear to view "struct" as the default position
to take, only making something a class if you absolutely have to. The
reverse is usually the case - make something a class unless you
absolutely definitely want value type semantics and don't want to
achieve something similar by making the class immutable (like string).
Structs behave "oddly" in a number of ways - all perfectly reasonable
in themselves, but potentially surprising in a world which mostly uses
reference types.
 
Dear Jon,

Can you think of one use of struct that is not in the framework?

PInvoke structures don't count.

I have yet to declare a struct. And I've been doing everything from web, to
databases, to gui to utils to soa.

How about you?

- Michael S
 
Michael said:
Are you sure you posted the right URL?
Absolutely.

Your only mention of structs are as in 'The LockToken returned by the Lock
method is a struct. It must be disposed in order to release the monitor'

Yup - the lock token is the only struct involved, but it's still a
struct :)
Which in by itself sounds weird. How does a struct implement IDispose?

=)

Gotcha

Nope, it just implements IDisposable in the normal way. So long as you
never actually cast it to IDisposable, no boxing is required. Here's a
sample program:

using System;

struct Foo : IDisposable
{
public void Dispose()
{
Console.WriteLine ("Disposed");
}
}

class Test
{
static void Main()
{
using (Foo f = new Foo())
{
}
}
}

Jon
 
Nope, it just implements IDisposable in the normal way. So long as you
never actually cast it to IDisposable, no boxing is required. Here's a
sample program:

Cool. You teach me something new everyday.
I kinda felt that I was wrong when I wrote gotcha and pressed send.

Guess I was, but I also got a fast reply with example.

Gotcha =)
- Michael S
 
Michael S said:
Dear Jon,

Can you think of one use of struct that is not in the framework?

PInvoke structures don't count.

I have yet to declare a struct. And I've been doing everything from web,
to databases, to gui to utils to soa.

How about you?

- Michael S

"Classes have the advantage of being reference types — passing a reference
is more efficient than passing a structure variable with all its data. On
the other hand, structures do not require allocation of memory on the global
heap." ... "Because you cannot inherit from a structure, structures should
be used only for objects that do not need to be extended. Use structures
when the object you wish to create has a small instance size, and take into
account the performance characteristics of classes versus structures. In
general, objects requiring a larger instance size should be created as a
class. Structures with large instance sizes cause degradation in performance
as the instance data is passed from method to method. Depending on how the
structure is allocated and used, however, a structure may be more efficient
even with a larger instance size. For example, a structure allocated and
passed around inside an array can be efficient."

--
ms-help://MS.MSDNQTR.2003FEB.1033/vbcon/html/vbconStandardModulesVsClassModulesInComponentAssemblies.htm
So yeah, I can think of one use...when you do not want to allocate memory on
the global heap or when needing a value-type, or when needing to pass a set
of data (via class or struct) around inside an array :)

HTH,
Mythran
 
After reading all of the comments:
Would it be better to have the marble a structure since it will only
hold static data and really have no methods. Then have the marble bag a
class that would hold an array of marble/s. This class then would have
methods like, HowManyMarbles(), Marble[] GetAllBlue(), etc.

pseudo code:
MarbleBag myBag = new MarbleBag;
Marble myMarble = new Marble;
myMarble.Color = "Blue";
myMarble.Size = .5F;
myMarble.Type = "Aggie";

myBag.Add(myMarble);

Marble[] myArrayOfMarbles;
myArrayOfMarbles = Marble.GetAllBlue;

Console.WriteLine(myArrayOfMarbles[0].Type); //output would be Aggie

Any thoughts. Thanks.
 
Russell said:
After reading all of the comments:
Would it be better to have the marble a structure since it will only
hold static data and really have no methods.

That makes no difference to whether something should be a class or a
struct.

Structs can have methods, classes don't have to have methods - it's
completely orthogonal. The main thing is, "Do I need to have value type
semantics?" If the answer is no, use a class.

Jon
 
So -

If I have an array[25] of an ITEM, where the ITEM has several arrays[10]
of Float[15] (similiar to a matrix), can I make the rough generalization:
1) If I pass this ITEM to a method, it would be better for the ITEM to
be a class so it passes a reference rather than a copy. The method will not
modify the ITEM, only return information about the ITEM.
 
Well actually your example isn't as expensive as it sounds - but it can
get very confusing! Arrays themselves are reference types (even for
value-type items), so if a struct holds an array, it actually just
holds a reference to the array on the managed heap. When the struct is
cloned, you just get two structs looking at the same array, but the
array still only exists once. This can get very confusing if the two
structs now start editing the single array as though it were a private
copy.

However (to answer the question) a class is cheaper still - all it
copies is the /reference/ to the (class) object on the managed heap,
which is essentially an integer type, so very cheap.

However: the main thing to decide is whether you want value-type or
reference-type semantics. Ref-type is more common, but value-type is
useful for some situations - i.e. representing compound data such as a
complex (imaginary) number, or a compound DateTime/TimeSpan interval.
It is almost never a good idea for structs to be mutable (editable
within their instance), as this can lead to all sorts of confusion over
whether you are editing the "actual" object or a shallow clone.

Marc
 

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

Back
Top