-2

Can anyone provide a realworld example of when a struct can be used?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Csharp
  • 2,916
  • 16
  • 50
  • 77

4 Answers4

2

A struct can be used when you have a complex return type for a method. i.e. you have to return several values, and they don't really warrant a full class's overhead.

GreenKiwi
  • 1,025
  • 13
  • 28
1

A struct is notion of a record, a datatype that aggregates a fixed set of labelled objects, possibly of different types, into a single object. Structs are often used to group and relate objects in some manner.

mtasic85
  • 3,905
  • 2
  • 19
  • 28
1

If you mean a C struct, a great example is fixed scalar types in compilers. For example:

struct myScalar {
    void *payload;
    size_t psz;
    unsigned int refs;
    enum {
        S_STR,
        S_INT,
        S_FLOAT,
        S_OBJECT_INSTANCE
    }type;
};

Or a union could be used. Not a robust example, but you get the idea. You can then do

switch(aVar.type){ ... }
Aiden Bell
  • 28,212
  • 4
  • 75
  • 119
0

Structs are great for helping you parse data that has been compressed to bits for sending over "The wire". You might have a bunch of bitfields to fill out a single byte, and a struct is a way to lay a template over this scrambled pile of variables and, without any real effort, change it into a collection of usable, easily referenced variables.

Bill K
  • 62,186
  • 18
  • 105
  • 157