Personal notes on software development.
For Java technologies check my dedicated site

Pages

A struct is a simple user-defined type, a lightweight alternative to a class. Structs are
similar to classes in that they may contain: [1]

  • constructors;
  • properties;
  • methods;
  • fields;
  • operators;
  • nested types;
  • indexers;
  • can implement multiple interfaces;


But there are also significant differences between classes and structs: [1]
  • structs don’t support inheritance or destructors;
  • class is a reference type, a struct is a value type;
  • performance: structs are somewhat more efficient in their use of memory in arrays (however, they can be less efficient when used in nongeneric collections. Collections that take objects expect references, and structs must be boxed. There is overhead in boxing and unboxing, and classes might be more efficient in some large collections);
  • performance: if you have a class that has, as its member variables, 10 structs instead of 10 objects, when that class is created on the heap, one big object is created (the class with its 10 structs) rather than 11 objects. That allows the garbage collector to do much less work when your containing class is ready to be destroyed;

Typically, a struct is used as a container for a small set of related variables, as shown in the following example: [2]
public struct CoOrds
{
    public int x, y;

    public CoOrds(int p1, int p2)
    {
        x = p1;
        y = p2;
    }
}


References

[1] - Book: Programming C# 3.0 (pag, 127)
[2] - MSDN: Types (C# Programming Guide)

No comments:

Post a Comment