Structures - real life examples?

There are many questions about SO regarding the differences between Structs and Classes in C #, and when to use one or the other. (The answer to one sentence: use structures if you need semantics of values.) There are many recommendations on how to choose one or the other, most of which boils down to: using a class if you do not meet these specific requirements, then use a struct.

It all makes sense to me.

However, I cannot find real examples of people using structures in the system. I am (semi-) new to C #, and I am having trouble representing a specific situation where structures are really the right choice (at least I haven't come across one yet).

So, I turn to the SO-brain. What are the cases when you actually used a structure in a system in which a class would not work?

+42
c # types struct
Aug 28 '09 at 20:44
source share
21 answers

Ok, the class will work for him, but an example that I might think is something like Point. Assuming this is the value of x and y, you can use struct.

struct Point { int x; int y; } 

In my opinion, I would rather have a simpler representation of a pair of integers than define using a class with instances when the actual object really doesn't have much (or any) behavior.

+20
Aug 28 '09 at 20:47
source share

I used a structure to represent geolocation

 struct LatLng { public decimal Lattitude { get; set; } public decimal Longitude { get; set; } } 

this is a single object, for example, I can add 2 LatLng together or perform other operations on this single object.

MSDN structure

The type of structure is suitable for representing light objects such as point, rectangle, and color. Although a dot can be thought of as a class, structure is more effective in some scenarios. For example, if you declare an array of 1000 Point features, you will allocate additional memory to reference each feature. In this case, the structure is cheaper.

Also, if you look at the primitive types Int32, decimal, double , etc., you will notice that they are all structs , which allows them to be value types, allowing them to implement certain important interfaces.

+17
Aug 28 '09 at 20:47
source share

Structures are also commonly used in graphics / rendering systems. There are many advantages to creating point / vector structures.

Rico Mariani has published an excellent value-based programming quiz . He discussed many reasons to prefer structures in specific situations and explained this in detail in his test report.

+13
Aug 28 '09 at 20:49
source share

The money structure is probably one of the most common, but the phone number or address is also common.

 public struct Money { public string Currency { get; set; } public double Amount { get; set; } } public struct PhoneNumber { public int Extension { get; set; } public int RegionCode { get; set; } //... etc. } public struct FullName { public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } } 

Keep in mind that in .NET your structures should not have more memory than 16 bytes, because if they get larger, the CLR must allocate additional memory.

Besides the fact that structs are "live" on the stack (and not heaps as reference types), you can consider using structures if you need to instantiate a lot of the same types of objects.

+7
Aug 28 '09 at 20:48
source share

A key example is a nullable types structure like int? . They use structures to preserve the semantics of int values, but provide a way to make them null without a box and turn them into reference types.

You would use a structure when you don't want to pass anything by reference. Suppose you have a dataset or object that you want to pass by value (i.e., everything that you pass to it works with its unique copy, not a reference to the original version), then the structure is the right type to use.

+5
Aug 28 '09 at 20:46
source share

They provide a default implementation for Object.GetHashCode (), so you can use a structure instead of a class when the object is a simple set of types without a reference that you want to use as keys to the dictionary.

They are also useful for PInvoke / interop or low-level network scenarios where you need precise control over the binary layout of the data structure. (go to www.pinvoke.net for a lot of interaction code that requires structures)

But in fact, I never use them myself. Do not sweat without using them.

+3
Aug 28 '09 at 20:52
source share

Mostly I try NOT to use them. I find that they confuse other developers on the team and therefore are not worth the effort. I just found one case to use it, a custom type type like Enum, we use a code generator to create from XML.

+2
Aug 28 '09 at 22:11
source share

The key for me is to determine if I want to keep the link to the same object.

Which makes sense when a struct is part of another object, but the entity itself.

In the example above with LatLong, which, for example, makes perfect sense. You need to copy the values ​​from one object to another, and not continue to reference the same object.

+1
Aug 28 '09 at 20:50
source share

I often use structs to represent the type value of a domain model that can be represented as an enumeration, but requires an arbitrary unlimited number of discrete values, or I want it to have additional behavior (methods) that you cannot add to the enumeration ... For example , in a recent project, many data items were associated with a specific calendar by Month, not by date. So I created a CalendarMonth structure with methods:

  • static CalendarMonth Parse (DateTime inValue);
  • static CalendarMonth Parse (inValue string);

and the TryParse () method,

  • static bool TryParse (string inValue, out CalendarMonth outVal);

And Properties

  • int Month {get; set; }
  • int Year {get; set; }
  • DateTime StartMonthLocal {get; set; }
  • DateTime StartMonthUTC {get; set; }
  • DateTime EndMonthLocal {get; set; }
  • DateTime EndMonthUTC {get; set; }

and etc.

+1
Aug 28 '09 at 20:59
source share

im usually not about "data density" in my business applications. I usually always use a class unless I specifically want the semantics of values

This means that I anticipate a situation where I want to compare two of these things, and I want them to appear the same if they have the same meaning. With classes, this is actually more work, because I need to override == ,! =, Equals and GetHashcode, that even if resharper does this for me, this is superfluous unnecessary code.

Therefore, in my opinion, always use classes if you do not know that you want these things to be compared by value (in this case, the value of the component)

+1
Aug 28 '09 at 22:35
source share

So, as I understand it, you never used DateTime (struct).

+1
Aug 30 '09 at 18:40
source share

I can’t believe that no one mentioned XNA : in XNA almost everything is struct . Therefore when you do

 Matrix rotation = Matrix.CreateRotationZ(Math.PiOver2); 

You really create a value type.

This is because, unlike application programming, there is a delay of a few milliseconds until the garbage collector is acceptable (we only get 16.6 ms to display the entire frame!), So we need to avoid distribution as much as possible so GC does not need to run so much.

This is especially true for the XBox 360, where the GC is nowhere near the quality of the PC - even on average, one distribution per frame can kill performance!

+1
Jun 30 2018-11-17T00:
source share

I worked in financial institutions where the requirements for caching and large-scale latency using structures were achieved. In principle, structures can save the garbage collector from work.

See the following examples:

http://00sharp.wordpress.com/2013/07/03/a-case-for-the-struct/ http://00sharp.wordpress.com/2013/07/04/a-case-for-the- structpart-2 /

+1
Jul 05 '13 at 6:44
source share

Basically, I use Structs to model geometric and mathematical data or when I need a data structure based on values.

0
Aug 28 '09 at 20:51
source share

The only time I ever used a structure was when I built a Fraction structure:

 public struct Fraction { public int Numerator {get;set;} public int Denominator {get; set;} //it then had a bunch of Fraction methods like Reduce, Add, Subtract etc... } 

I felt that it represents a value, like the built-in value types, and therefore encoding against it would be more natural if it behaves like a value type.

0
Aug 28 '09 at 22:16
source share

I think the .Net Framework is real life. See the list in the "Structures" section:

System namespace

0
Aug 28 '09 at 23:02
source share

In some critical situations, a structure (value type and, therefore, allocated from the stack) may be better than a class (reference type and, therefore, allocated from the heap). Joe Duffy blog post " One-word write / write lock " shows a real use of this.

0
Aug 29 '09 at 2:11
source share

In the past, I created StorageCapacity. It represented 0 bytes for N exabytes (could rise to yottabyte, but exa seemed enough at that time). The structure made sense since I worked for a storage management company. You might think that it was pretty simple: structure with StorageUnit (enumeration) and quantity (I used decimal). But when you add in conversions, operators and classes to support formatting, parsing, etc., it adds up.

The abstraction was useful so that you could use any StorageCapacity and represent it in bytes, kilobytes, etc. without the need to multiply or divide by 1024 many times.

0
Aug 30 '09 at 16:31
source share

I explained the reasons for using structures already in another place ( When to use struct in C # ), and I used structures for these reasons in real projects:

I would choose to use structures for performance reasons if I needed to store a large number of the same type of element in an array, which might happen when processing images.

You need to use structures to transfer structured data between C # and C ++.

If I have no reason to use them, I try to avoid them.

I know that some people like to use them to implement value semantics, but I find that this behavior is so different from the "normal" behavior of assignment classes (in C #) that you find it hard to track errors because one isn’t remembered that an object that was assigned or had this behavior because it was implemented as a structure instead of a class. (This has happened to me more than once, so I give this warning since I was actually burnt by the obsessive use of C # structures.)

0
Aug 30 '09 at 18:38
source share

I'm not sure how much this is used, but today I found that although you cannot have instance field iniators in structures, you can in classes.

Therefore, the following code will give compilation errors, but if you change "struct" to "class", it will compile.

  public struct ServiceType { public bool backEnd { get; set; } public bool frontEnd { get; set; } public string[] backEndServices = { "Service1", "Service2" }; public string[] frontEndServices = { "Service3", "Service4" }; } 
0
Oct 13 '09 at 17:00
source share

The structure in C # in your heart is no more and no less than a bunch of variables glued together with duct tape. If you want each variable of a certain type to represent a bunch of independent but related variables (such as point coordinates) attached with duct tape, it is often better to use an open field structure than a class, regardless of whether a bunch means two or twenty. Note that although the recommendations for a structured Microsoft class are appropriate for data types that encapsulate a single value, it should not be considered applicable to types whose purpose is to encapsulate independent but related values. The greater the degree of independence of the variables, the greater the benefits of using an open field structure.

If you want to use a class to encapsulate a group of independent variables, there are two ways to do this, none of which are terribly convenient. An immutable class can be used, in which case any non-zero storage location of this type of class encapsulates the values ​​stored in the instance identified by it, and one storage location can be copied to another so that a new one encapsulates the same values. Unfortunately, changing one of the values ​​encapsulated by the location of the repository usually requires creating a new instance that is exactly the same as the old one, except that the value has changed. For example, if you have a pt variable of type Immutable3dPoint , and one wanted to increase pt.X by one, you would need to do something like: pt = new Immutable3dPoint(pt.X+1, pt.Y, pt.Z); Perhaps it is permissible if the type only encapsulates three values, but rather annoying if there are a lot of them.

Another class-based approach is to use a mutable class; this usually requires that everyone ensure that each storage location of a class type contains a single reference anywhere in the universe for an instance of that class. When you create a storage location, you need to create a new instance and save the link there. If you want to copy values ​​from storage location P to storage location Q , to another, you need to copy all fields or properties from one instance to another (possibly using a method of type CopyFrom and say Q.CopyFrom(P); Note that if one of these, Q=P; says that may seem to work, but future attempts to change P will also change Q and vice versa. Variable classes can work, and they can be effective from time to time, but it’s very easy to damage things.

Open-field structures combine the convenient semantics of the values ​​of immutable classes with the convenient piecewise modifications allowed by mutable classes. Large structures are copied more slowly than references to immutable objects, but the cost of modifying part of the structure of an open field depends only on the degree of modification, and not on the overall size of the structure. In contrast, the cost of changing one piece of data encapsulated in an immutable class type will be proportional to the total size of the class.

0
Nov 12 '13 at
source share



All Articles