473,804 Members | 3,273 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why are some types implemented as struct?

I know the basic differences between a struct and a class, but
apparently not good enough to know why some types/concepts are
implemented as struct whereas most types are implemented as class.
For example, why is DateTime implemented as a struct? Why is BitArray
implemented as a class, but BitVector32 a struct?

In general, in OO design, how do we determine if we should use struct
or class?
Jul 28 '08
12 1565
On Jul 28, 7:33*pm, Author <gnewsgr...@gma il.comwrote:
In general, in OO design, how do we determine if we should use struct
or class?
A few distinguishing traits:

1) It is data-centric, not behavior-centric - e.g. Point is just a
tuple of two ints, Person is an entity with encapsulated operations.
Most methods on structs are just helpers to manipulate data, and could
usually be refactored as external methods. Most methods on classes
should encapsulate business logic related to entities those classes
model.

2) It has no identity - two structs are equal if the data within is
the same; for two structs with the same data, there is no way to
distinguish them, and using one in place of the other should give
identical results for any operation. C# enforces this by requiring
structs to define at least one field (since two identityless objects
which don't have data cannot be distinguished at all, so the result is
effectively a singleton). For example, if you get a Point with X=2 and
Y=3 from the first method, it is guaranteed that whether you pass that
same Point on to the second method, or create your own new Point with
the same values of X and Y and then pass that to the second method,
the actions performed by the second method will be exactly the same.
On the other hand, if you have two different Person instances, they
typically refer to two different people, even if their names (and
other data) match, so passing one instead of another to a business
method will do a different thing. In C#, this manifests itself in the
fact that classes have operator== which compares references (i.e. does
an identity comparison), and default implementation of Equals() for
classes also does reference comparison, while for structs Equals()
compares values of all fields, and there is no way to do a reference
comparison.

3) It is atomic with respect to updates - you cannot take an existing
Point and change just the X coordinate - the result would always be a
new Point. In C# terms, this means that structs are immutable (this
isn't enforced by the compiler, but is strongly recommended to follow
the practice nonetheless).

Simply put, the design difference between a struct and a class is the
difference between raw data (tuple, record, etc) and an entity. The
line can be blurry sometimes, but usually it is fairly obvious for
every specific case.

Of course, in real world, decision on using class vs struct is often
made for performance reasons - a good example is List<T>.Enumera tor,
which is a struct, though it doesn't really fit the definition above.
Jul 29 '08 #11

"Peter Duniho" <Np*********@nn owslpianmk.comw rote in message
news:op******** *******@petes-computer.local. ..
On Mon, 28 Jul 2008 11:53:40 -0700, Fredo <fr***@hotmail. comwrote:
>"Peter Morris" <mr*********@SP AMgmail.comwrot e in message
news:%2******* *********@TK2MS FTNGP06.phx.gbl ...
>>Nearly every time I have designed something as a struct I have later
discovered I need to be able to change the values in it and ended up
converting it to a class, so now I just don't bother with them any more.

You can change values in a struct as easily as you can in a class.

Well, yes and no.

There are some serious problems with making a struct mutable. The fact
that structs are _copied_ rather than references leads to code that either
doesn't work as expected (you think you've changed an instance but have
only changed a copy of an instance), or just doesn't compile, or is more
inconvenient than it could or should be.

Pete
Pete,

You're absolutely correct. I guess part of it is mentality.

I generally reserve structs for things that I think of as "non-trivial
datatypes". For example, point, size, rect, vector (mathematical, not in the
array sense), and so forth, are little more than data types that are
slightly more complex than the basic data types. So the fact that they pass
by value instead of by reference, just like the basic data types, makes
sense.

They can also be useful in the plain old C sense of struct (a collection of
related variables), though I generally go with a class in that case.

Pete
Jul 29 '08 #12
On Tue, 29 Jul 2008 07:31:58 -0700, Pavel Minaev <in****@gmail.c omwrote:
On Jul 28, 7:33Â*pm, Author <gnewsgr...@gma il.comwrote:
>In general, in OO design, how do we determine if we should use struct
or class?

A few distinguishing traits:

1) It is data-centric, not behavior-centric [...]

2) It has no identity - two structs are equal if the data within is
the same [...]

3) It is atomic with respect to updates [...]
Of course, all of the above three apply to the String type, which is _not_
a struct.

All due respect, I think you missed one of the most important aspects of a
struct: it's usually something small, so that copying it around isn't
costly. And I think that there are a number of examples of classes that
would fit your three criteria but still are better as classes than structs.

Pete
Jul 30 '08 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2003
by: Guilherme Pinto | last post by:
Hello. I am reading the book written by Bjarne Stroustrup called " The C++ Programming Language - Special Edition" and had a doubt which a think is really important to distinguish between the main features of modules, namespaces, and User-Defined types. The text above was copied from page 31. --------------------------------------------------------
193
9656
by: Michael B. | last post by:
I was just thinking about this, specifically wondering if there's any features that the C specification currently lacks, and which may be included in some future standardization. Of course, I speak only of features in the spirit of C; something like object-orientation, though a nice feature, does not belong in C. Something like being able to #define a #define would be very handy, though, e.g: #define DECLARE_FOO(bar) #define...
11
3194
by: theshowmecanuck | last post by:
As a matter of academic interest only, is there a way to programmatically list the 'c' data types? I am not looking for detail, just if it is possible, and what function could be used to accomplish it. For example: int main void() { while there are more data types { print next data type; }
48
2185
by: yezi | last post by:
Hi, all: I want to record some memory pointer returned from malloc, is possible the code like below? int memo_index; int i,j; char *tmp; for (i=0;i<10;i++){
3
2676
by: Bear | last post by:
Hello there How come it's possible to add values of the type "int" into an ArrayList when the Add member function only accepts values of type "object"? Is an int just a "typedef" of the Int32 structure and, if so, does the runtime system load a value type onto the stack even though it only needs to load a primitive type? -- Best regards
1
1782
by: albert_reade | last post by:
Hello I was wondering if someone could please help me understand what I need to do in order to get this project to work. I just need some hints or a push in the right direction to get this to work, thanks. Design the Array of Expected Events, AEE, required by the interrupt system. Each entry i, 0 <= i < 6, in this array contains three fields, AEE.IIC, AEE.InterruptHandler, AEE.WaitingQueue. These elds are designed such that they can...
19
1304
by: Marco Trapanese | last post by:
Hello, I need some help to understand what I'm doing :) I'm writing code for an embedded system and I need to create a navigable menu system. I'm going to use these structures: typedef struct { char *name; int type;
2
2135
by: Stefan Hoffmann | last post by:
hi @all, has anybody an explanation, why string? is not allowed for an auto-implemented property? namespace Test { class Class1 { int? NullableInt { get; set; }
50
4522
by: Juha Nieminen | last post by:
I asked a long time ago in this group how to make a smart pointer which works with incomplete types. I got this answer (only relevant parts included): //------------------------------------------------------------------ template<typename Data_t> class SmartPointer { Data_t* data; void(*deleterFunc)(Data_t*);
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9584
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10583
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10323
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7622
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6854
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3822
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2995
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.