Robel Tech 🚀

When should I use a struct rather than a class in C

February 20, 2025

📂 Categories: C#
🏷 Tags: Struct
When should I use a struct rather than a class in C

Successful C, some structs (buildings) and courses are cardinal gathering blocks for creating customized information sorts, however they service antithetic functions and person chiseled traits. Knowing these variations is cardinal to penning businesslike and maintainable C codification. Selecting the correct information kind—struct oregon people—frequently hinges connected whether or not you demand a worth kind oregon a mention kind. This seemingly tiny discrimination tin importantly contact show and representation direction. This article dives heavy into the nuances of structs and lessons successful C, offering broad tips connected once to usage all, on with applicable examples to solidify your knowing.

Worth Sorts vs. Mention Sorts

The center quality betwixt structs and courses lies successful however they are dealt with successful representation. Structs are worth varieties, which means a adaptable of a struct kind straight comprises the struct’s information. Once you transcript a struct adaptable, you make a wholly fresh transcript of the information. Courses, connected the another manus, are mention varieties. A adaptable of a people kind holds a mention to the entity’s information successful representation. Copying a people adaptable lone duplicates the mention, not the underlying information. This discrimination impacts representation utilization and show.

Deliberation of it similar this: ideate you person a blueprint (people) and a gathering (entity). Aggregate group tin person a transcript of the blueprint (references), however location’s lone 1 gathering. With structs, it’s arsenic if everybody will get their ain gathering—a wholly abstracted transcript.

For illustration:

// Struct Illustration Component p1 = fresh Component(1, 2); Component p2 = p1; // Copies the worth p2.X = three; // Modifies lone p2 // p1.X is inactive 1 // People Illustration MyClass c1 = fresh MyClass(); MyClass c2 = c1; // Copies the mention c2.Worth = 5; // Modifies some c1 and c2 // c1.Worth is present 5 

Once to Usage Structs

Structs are mostly most popular for tiny, elemental information buildings that are often copied. They are perfect once you demand a kind to correspond a azygous worth, similar a component successful 2nd abstraction, a colour, oregon a analyzable figure. Utilizing structs successful these situations tin better show by lowering the overhead related with heap allocations and rubbish postulation.

Cardinal situations wherever structs excel:

  • Representing elemental information buildings.
  • Immutability is desired (much connected this future).
  • Show is captious and copying information is predominant.

For illustration, representing a 3D component arsenic a struct is extremely businesslike:

national struct Point3D { national interval X; national interval Y; national interval Z; } 

Once to Usage Lessons

Courses are much versatile than structs and are the most popular prime successful about eventualities. They are indispensable once you demand options similar inheritance, polymorphism, and analyzable behaviour. If your information kind requires strategies to manipulate its inner government, a people is about ever the amended prime.

Take courses once:

  • You demand mention kind semantics.
  • You necessitate inheritance oregon polymorphism.
  • The information construction is ample oregon analyzable.
  • Mutability is required.

For case, modeling a “Buyer” with properties similar sanction, code, and command past would course beryllium a people.

Immutability and Information Integrity

Structs tin promote immutability, a almighty conception successful programming. An immutable entity can not beryllium modified last it’s created. This simplifies reasoning astir codification and reduces the hazard of unintended broadside results. Piece not inherently immutable, structs lend themselves fine to immutable plan. By making each fields publication-lone, you tin make immutable structs, guaranteeing information integrity.

See this illustration of an immutable struct:

national struct ImmutablePoint { national readonly int X; national readonly int Y; national ImmutablePoint(int x, int y) { X = x; Y = y; } } 

Show Issues

Piece structs tin message show benefits successful definite situations, it’s important to debar untimely optimization. Chart your codification to place real show bottlenecks earlier making selections primarily based solely connected the possible advantages of structs. Overuse of structs tin pb to much analyzable and little maintainable codification.

See the measurement of the information construction. Ample structs tin beryllium inefficient to walk about arsenic parameters due to the fact that they are copied by worth. Successful specified circumstances, utilizing lessons and passing references is mostly much businesslike.

Larn much astir show optimization successful C.

FAQ: Structs vs. Lessons

Q: Tin structs person strategies?

A: Sure, structs tin person strategies, constructors, and properties, conscionable similar courses. Nevertheless, it’s mostly really helpful to support structs elemental and centered connected information.

Q: Tin structs inherit from another structs oregon lessons?

A: Nary, structs can’t inherit from another structs oregon courses, nor tin they beryllium utilized arsenic a basal for another varieties. They implicitly inherit from Scheme.ValueType.

Selecting betwixt a struct and a people successful C includes knowing the commercial-offs betwixt worth sorts and mention sorts. By contemplating components similar information dimension, mutability necessities, and show implications, you tin brand knowledgeable selections that pb to cleaner, much businesslike, and maintainable codification. Retrieve to prioritize codification readability and maintainability complete untimely optimization. Take the information kind that champion fits the circumstantial wants of your exertion. Research additional sources and delve deeper into precocious C ideas to heighten your programming expertise. See the contact of your prime connected representation direction and rubbish postulation, particularly for often utilized information buildings.

[Infographic evaluating structs and lessons]

Outer Assets:

  1. Microsoft Docs: Worth Sorts
  2. Microsoft Docs: Mention Varieties
  3. Stack Overflow: Once to Usage Structs vs. Courses

Question & Answer :
Once ought to you usage struct and not people successful C#? My conceptual exemplary is that structs are utilized successful occasions once the point is simply a postulation of worth sorts. A manner to logically clasp them each unneurotic into a cohesive entire.

I got here crossed these guidelines present:

  • A struct ought to correspond a azygous worth.
  • A struct ought to person a representation footprint little than sixteen bytes.
  • A struct ought to not beryllium modified last instauration.

Bash these guidelines activity? What does a struct average semantically?

The origin referenced by the OP has any credibility …however what astir Microsoft - what is the stance connected struct utilization? I sought any other studying from Microsoft, and present is what I recovered:

See defining a construction alternatively of a people if cases of the kind are tiny and generally abbreviated-lived oregon are generally embedded successful another objects.

Bash not specify a construction except the kind has each of the pursuing traits:

  1. It logically represents a azygous worth, akin to primitive sorts (integer, treble, and truthful connected).
  2. It has an case dimension smaller than sixteen bytes.
  3. It is immutable.
  4. It volition not person to beryllium boxed often.

Microsoft constantly violates these guidelines

Fine, #2 and #three anyhow. Our beloved dictionary has 2 inner structs:

[StructLayout(LayoutKind.Sequential)] // default for structs backstage struct Introduction //<Tkey, TValue> { // Position codification astatine *Mention Origin } [Serializable, StructLayout(LayoutKind.Sequential)] national struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable, IDictionaryEnumerator, IEnumerator { // Position codification astatine *Mention Origin } 

*Mention Origin

The ‘JonnyCantCode.com’ origin acquired three retired of four - rather forgivable since #four most likely wouldn’t beryllium an content. If you discovery your self boxing a struct, rethink your structure.

Fto’s expression astatine wherefore Microsoft would usage these structs:

  1. All struct, Introduction and Enumerator, correspond azygous values.
  2. Velocity
  3. Introduction is ne\’er handed arsenic a parameter extracurricular of the Dictionary people. Additional probe reveals that successful command to fulfill implementation of IEnumerable, Dictionary makes use of the Enumerator struct which it copies all clip an enumerator is requested …makes awareness.
  4. Inner to the Dictionary people. Enumerator is national due to the fact that Dictionary is enumerable and essential person close accessibility to the IEnumerator interface implementation - e.g. IEnumerator getter.

Replace - Successful summation, recognize that once a struct implements an interface - arsenic Enumerator does - and is formed to that carried out kind, the struct turns into a mention kind and is moved to the heap. Inner to the Dictionary people, Enumerator is inactive a worth kind. Nevertheless, arsenic shortly arsenic a methodology calls GetEnumerator(), a mention-kind IEnumerator is returned.

What we don’t seat present is immoderate effort oregon impervious of demand to support structs immutable oregon sustaining an case dimension of lone sixteen bytes oregon little:

  1. Thing successful the structs supra is declared readonly - not immutable
  2. Measurement of these struct might beryllium fine complete sixteen bytes
  3. Introduction has an undetermined life (from Adhd(), to Distance(), Broad(), oregon rubbish postulation);

And … four. Some structs shop TKey and TValue, which we each cognize are rather susceptible of being mention varieties (added bonus data)

Hashed keys however, dictionaries are accelerated successful portion due to the fact that instancing a struct is faster than a mention kind. Present, I person a Dictionary<int, int> that shops 300,000 random integers with sequentially incremented keys.

Capability: 312874
MemSize: 2660827 bytes
Accomplished Resize: 5ms
Entire clip to enough: 889ms

Capability: figure of parts disposable earlier the inner array essential beryllium resized.

MemSize: decided by serializing the dictionary into a MemoryStream and getting a byte dimension (close adequate for our functions).

Accomplished Resize: the clip it takes to resize the inner array from 150862 parts to 312874 components. Once you fig that all component is sequentially copied by way of Array.CopyTo(), that ain’t excessively shabby.

Entire clip to enough: admittedly skewed owed to logging and an OnResize case I added to the origin; nevertheless, inactive awesome to enough 300k integers piece resizing 15 instances throughout the cognition. Conscionable retired of curiosity, what would the entire clip to enough beryllium if I already knew the capability? 13ms

Truthful, present, what if Introduction have been a people? Would these instances oregon metrics truly disagree that overmuch?

Capability: 312874
MemSize: 2660827 bytes
Accomplished Resize: 26ms
Entire clip to enough: 964ms

Evidently, the large quality is successful resizing. Immoderate quality if Dictionary is initialized with the Capability? Not adequate to beryllium afraid with … 12ms.

What occurs is, due to the fact that Introduction is a struct, it does not necessitate initialization similar a mention kind. This is some the appearance and the bane of the worth kind. Successful command to usage Introduction arsenic a mention kind, I had to insert the pursuing codification:

/* * Added to fulfill initialization of introduction components -- * this is wherever the other clip is spent resizing the Introduction array * **/ for (int i = zero ; i < premier ; i++) { destinationArray[i] = fresh Introduction( ); } /* *********************************************** */ 

The ground I had to initialize all array component of Introduction arsenic a mention kind tin beryllium recovered astatine MSDN: Construction Plan. Successful abbreviated:

Bash not supply a default constructor for a construction.

If a construction defines a default constructor, once arrays of the construction are created, the communal communication runtime robotically executes the default constructor connected all array component.

Any compilers, specified arsenic the C# compiler, bash not let constructions to person default constructors.

It is really rather elemental and we volition get from Asimov’s 3 Legal guidelines of Robotics:

  1. The struct essential beryllium harmless to usage
  2. The struct essential execute its relation effectively, except this would break regulation #1
  3. The struct essential stay intact throughout its usage until its demolition is required to fulfill regulation #1

what bash we return distant from this: successful abbreviated, beryllium liable with the usage of worth sorts. They are speedy and businesslike, however person the quality to origin galore surprising behaviors if not decently maintained (i.e. unintentional copies).