473,837 Members | 1,426 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Structures and Classes

OK, I admit that I have been programming since before C++ was invented,
and I have developed more than my share of assembly language systems,
and even contributed to operating system and compiler systems over the
years. I have developed code in more than 30 distinct programming
languages for a wide cariety of industries. But this issue of structures
in C# is beginning to annoy me.

I should also make it clear that I am not a big supporter of the C++
convention that the only difference between a class and a structure is
whether or not the data members, private or otherwise, can be treated as
a single entity. I have made strong cases in C++ code for the structure
to be a data member of a class, not make the member functions part of
the structure.

There are times when a structure is extemely useful, however, such as
when communicating with an exising applicaiton or file that stores its
data in a specific layout that is well defined using a C++ structure.

I have been using C# for some time now, and I must admit that I find the
language a significant improvement over C++ (aside from speed at times).
I especially like how enumerations are a part of the language - I
believe the C# approach to be far better than the C/C++ approach (not
claiming this approach is unique to C#). But this issue of structures
vs. classes keeps raising its head.

I sometimes write code, in the form of services, that must communicate
with custom device drivers, often passing the control structures in
predefined record layouts. In C++ these are simple structures, and I
have been using the same in C# most of the time -- except where the
structures are not simple, and it became much easier to define a class
with MarshalIn() and MarshalOut() methods that transfer the data members
sequentially. This is especially true when some of the structures nest
other structures several levels deep.

The one thing that bothers me the most is this concept that a structure
is a 'value' type and a class is an object type. This means that there
are certain times when passing structures around in code rquires
'boxing' or other special steps, or it cannot be done cleanly.

What happens in C# when I define a class that has a structure as its
data member (perhaps its only data member)? The structure is still
allocated on the stack, as opposed to from the heap, and so there would
still appear to be some problems with passing things around.

I am coming to the conclusion that the usefullness of structures in C#
is very limited and effective only in isolated cases. It would seem that
the main C# code should always use classes with atomic data members, and
either create and use the structure only as part of I/O operations (some
overhead in the creation and population of the structure), or use custom
Marshal methods to deal with each atomic field on its own. The style of
defining a structure to be used as a single I/O or parameter object and
then adding methods to the structure definition so it also appears to be
a class is not something good or effective in C# (although some C++ code
I have encountered relies heavily on this approach).

Am I wrong here? Have I missed something?

-ken
Nov 17 '05 #1
6 4491
Ken,

At times I agree with you on this. It depends on the situation though.
For example, I see Point and Size as being really basic types which don't
need class semantics, and should be treated as value types. However, I
don't see many other uses (except in the case where you want to implement a
rollback mechanism of some kind, and implement IDisposable on the structure,
and use that to perform rollback operations in a using statement, and don't
want to allocate an object on the heap to do this).

There is one part of your post that is incorrect. You state:

What happens in C# when I define a class that has a structure as its
data member (perhaps its only data member)? The structure is still
allocated on the stack, as opposed to from the heap, and so there would
still appear to be some problems with passing things around.

When you have a field in a class that is a value type, that value type
is not copied on the stack. The memory for that value type is in the memory
taken up by the class instance itself, and moves where the instance moves.
It's the same as having a field of type int or bool, it's just part of the
type.

Basically, what it comes down to is you use structures in your
programming where you feel copy-on-assignment semantics are appropriate.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Ken Allen" <ke******@sympa tico.ca> wrote in message
news:uu******** *****@TK2MSFTNG P15.phx.gbl...
OK, I admit that I have been programming since before C++ was invented,
and I have developed more than my share of assembly language systems, and
even contributed to operating system and compiler systems over the years.
I have developed code in more than 30 distinct programming languages for a
wide cariety of industries. But this issue of structures in C# is
beginning to annoy me.

I should also make it clear that I am not a big supporter of the C++
convention that the only difference between a class and a structure is
whether or not the data members, private or otherwise, can be treated as a
single entity. I have made strong cases in C++ code for the structure to
be a data member of a class, not make the member functions part of the
structure.

There are times when a structure is extemely useful, however, such as when
communicating with an exising applicaiton or file that stores its data in
a specific layout that is well defined using a C++ structure.

I have been using C# for some time now, and I must admit that I find the
language a significant improvement over C++ (aside from speed at times). I
especially like how enumerations are a part of the language - I believe
the C# approach to be far better than the C/C++ approach (not claiming
this approach is unique to C#). But this issue of structures vs. classes
keeps raising its head.

I sometimes write code, in the form of services, that must communicate
with custom device drivers, often passing the control structures in
predefined record layouts. In C++ these are simple structures, and I have
been using the same in C# most of the time -- except where the structures
are not simple, and it became much easier to define a class with
MarshalIn() and MarshalOut() methods that transfer the data members
sequentially. This is especially true when some of the structures nest
other structures several levels deep.

The one thing that bothers me the most is this concept that a structure is
a 'value' type and a class is an object type. This means that there are
certain times when passing structures around in code rquires 'boxing' or
other special steps, or it cannot be done cleanly.

What happens in C# when I define a class that has a structure as its data
member (perhaps its only data member)? The structure is still allocated on
the stack, as opposed to from the heap, and so there would still appear to
be some problems with passing things around.

I am coming to the conclusion that the usefullness of structures in C# is
very limited and effective only in isolated cases. It would seem that the
main C# code should always use classes with atomic data members, and
either create and use the structure only as part of I/O operations (some
overhead in the creation and population of the structure), or use custom
Marshal methods to deal with each atomic field on its own. The style of
defining a structure to be used as a single I/O or parameter object and
then adding methods to the structure definition so it also appears to be a
class is not something good or effective in C# (although some C++ code I
have encountered relies heavily on this approach).

Am I wrong here? Have I missed something?

-ken

Nov 17 '05 #2
Hello Ken,

You can find this discussion of some interest (mind the line wraps):

http://groups-beta.google.com/group/...cd85ecd5de4862

--
Sincerely,
Dmytro Lapshyn [Visual Developer - Visual C# MVP]
"Ken Allen" <ke******@sympa tico.ca> wrote in message
news:uu******** *****@TK2MSFTNG P15.phx.gbl...
OK, I admit that I have been programming since before C++ was invented,
and I have developed more than my share of assembly language systems, and
even contributed to operating system and compiler systems over the years.
I have developed code in more than 30 distinct programming languages for a
wide cariety of industries. But this issue of structures in C# is
beginning to annoy me.

I should also make it clear that I am not a big supporter of the C++
convention that the only difference between a class and a structure is
whether or not the data members, private or otherwise, can be treated as a
single entity. I have made strong cases in C++ code for the structure to
be a data member of a class, not make the member functions part of the
structure.

There are times when a structure is extemely useful, however, such as when
communicating with an exising applicaiton or file that stores its data in
a specific layout that is well defined using a C++ structure.

I have been using C# for some time now, and I must admit that I find the
language a significant improvement over C++ (aside from speed at times). I
especially like how enumerations are a part of the language - I believe
the C# approach to be far better than the C/C++ approach (not claiming
this approach is unique to C#). But this issue of structures vs. classes
keeps raising its head.

I sometimes write code, in the form of services, that must communicate
with custom device drivers, often passing the control structures in
predefined record layouts. In C++ these are simple structures, and I have
been using the same in C# most of the time -- except where the structures
are not simple, and it became much easier to define a class with
MarshalIn() and MarshalOut() methods that transfer the data members
sequentially. This is especially true when some of the structures nest
other structures several levels deep.

The one thing that bothers me the most is this concept that a structure is
a 'value' type and a class is an object type. This means that there are
certain times when passing structures around in code rquires 'boxing' or
other special steps, or it cannot be done cleanly.

What happens in C# when I define a class that has a structure as its data
member (perhaps its only data member)? The structure is still allocated on
the stack, as opposed to from the heap, and so there would still appear to
be some problems with passing things around.

I am coming to the conclusion that the usefullness of structures in C# is
very limited and effective only in isolated cases. It would seem that the
main C# code should always use classes with atomic data members, and
either create and use the structure only as part of I/O operations (some
overhead in the creation and population of the structure), or use custom
Marshal methods to deal with each atomic field on its own. The style of
defining a structure to be used as a single I/O or parameter object and
then adding methods to the structure definition so it also appears to be a
class is not something good or effective in C# (although some C++ code I
have encountered relies heavily on this approach).

Am I wrong here? Have I missed something?

-ken


Nov 17 '05 #3
Nicholas Paldino [.NET/C# MVP] wrote:
Ken,

At times I agree with you on this. It depends on the situation though. <snip/> Basically, what it comes down to is you use structures in your
programming where you feel copy-on-assignment semantics are appropriate.

Hope this helps.


Yes, this is the basic conclustion that I was coming to (thank you for
the correction on the structure as a class data member; I had meant to
pose that more as a question).

I do see value of wrapping the structure inside a class when the
structure contents are to be used as part of communication with another
component, permitting the buffer to be read and written as a unit
(although marshalling may still be involved).

My problems lie in the fact that 90% of the projects I consider deal
with communication with existing (unmanaged) components, and when the
component is in the kernel, I am forced to use unmanaged Win32 API calls
(DeviceIoContro l), which means marshalling is involved in one manner or
another.

This is where I am forced to selected between marshalling a structure or
marshalling the individual data members themselves. Writing interop code
is not somthing Visual Studio makes easier!

-ken
Nov 17 '05 #4
Ken Allen <ke******@sympa tico.ca> wrote:

<snip>
What happens in C# when I define a class that has a structure as its
data member (perhaps its only data member)? The structure is still
allocated on the stack, as opposed to from the heap, and so there would
still appear to be some problems with passing things around.
No, that's not true. The idea that value types always end up on the
stack is a mistake due to people being lazy when trying to explain what
goes where.

See http://www.pobox.com/~skeet/csharp/memory.html
I am coming to the conclusion that the usefullness of structures in C#
is very limited and effective only in isolated cases.
Pretty limited, yes - basically where you really need a value type,
which is pretty rarely given that many useful ones are already in the
framework.

I don't see why that's a problem though - it's just not the same as how
C/C++ viewed structures.
It would seem that
the main C# code should always use classes with atomic data members, and
either create and use the structure only as part of I/O operations (some
overhead in the creation and population of the structure), or use custom
Marshal methods to deal with each atomic field on its own. The style of
defining a structure to be used as a single I/O or parameter object and
then adding methods to the structure definition so it also appears to be
a class is not something good or effective in C# (although some C++ code
I have encountered relies heavily on this approach).


In what way does adding methods to the structure make it "appear to be
a class"? You need to forget the concept that structures are for data
only - the difference between structures and classes is just that
structures are value types and classes are reference types.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #5
Ken,

You know you can marshal classes, right? You don't ^have^ to use
structures. You can apply the marshaling attributes to a class and it
should work. There are some slight differences, but for the most part, it
works.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Ken Allen" <ke******@sympa tico.ca> wrote in message
news:uO******** ******@TK2MSFTN GP14.phx.gbl...
Nicholas Paldino [.NET/C# MVP] wrote:
Ken,

At times I agree with you on this. It depends on the situation
though.

<snip/>
Basically, what it comes down to is you use structures in your
programming where you feel copy-on-assignment semantics are appropriate.

Hope this helps.


Yes, this is the basic conclustion that I was coming to (thank you for the
correction on the structure as a class data member; I had meant to pose
that more as a question).

I do see value of wrapping the structure inside a class when the structure
contents are to be used as part of communication with another component,
permitting the buffer to be read and written as a unit (although
marshalling may still be involved).

My problems lie in the fact that 90% of the projects I consider deal with
communication with existing (unmanaged) components, and when the component
is in the kernel, I am forced to use unmanaged Win32 API calls
(DeviceIoContro l), which means marshalling is involved in one manner or
another.

This is where I am forced to selected between marshalling a structure or
marshalling the individual data members themselves. Writing interop code
is not somthing Visual Studio makes easier!

-ken

Nov 17 '05 #6
Nicholas Paldino [.NET/C# MVP] wrote:
Ken,

You know you can marshal classes, right? You don't ^have^ to use
structures. You can apply the marshaling attributes to a class and it
should work. There are some slight differences, but for the most part, it
works.

Is one assured of the order in which data members in a class will be
marhalled? One of the benefits of using a structure marked as sequential
layout is that one is assured bf the byte ordering for the marshalling.
It is not intuitive that a class would marshal as cleanly, especially
when the data memebers are strings or other reference objects - it would
seem that a 'field by field' marshalling procedure would be more
effective (but more coding effort?).

-ken
Nov 17 '05 #7

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

Similar topics

1
2739
by: kazack | last post by:
Hi all it's me again with another question as I got further in my book. The chapter I am in covers structres, abstract data and classes. I only read through to the end of the coverage on structures. Trying to comprehend this is harder than I thought it was going to be. I should of just skipped this chapter and went right into pointers since they seem to be easier to use. But anyways here i smy question: you define a structure...
1
741
by: Bob Rock | last post by:
Hello, in the last few days I've made my first few attempts at creating mixed C++ managed-unmanaged assemblies and looking aftwerwards with ILDASM at what is visible in those assemblies from a managed point-of-view I've noticed that: 1) for each managed and unmanaged C function (not C++ classes) I get a public managed static method (defined on a 'Global Functions' class) in the generated assembly with an export name of the form...
6
2644
by: moi | last post by:
hi, im fairly new to c++ and as part of a module at uni im learning it. i know the basics i suppose, but as our final hand-in we have to alter code we wrote for an earlier assignment to use classes as opposed to structures. the program basically modelled a simple polygon using point, line and polyogon structures. and had various functions to find the properties of the shape such as area, perimeter, etc. the question reads along the...
14
3811
by: Pratts | last post by:
I am a new one who have joined u plz try to help me bcoz i could not find ny sutiable answer foer this Question Qus>>why do we need classes when structures provide similar functionality??
6
7675
by: nick | last post by:
I have tried finding an answer to this, but most people just explain classes as a more modular way to program. It seems to me that (forgetting OO programming which I don't quite understand) the structures in C are the same as classes in another language such as C++ or Java only missing the ability to make the data private. I've never had this explained sufficiently and would appreciate a good answer. It doesn't need to be Mickey Mouse,...
14
15094
by: pmclinn | last post by:
I've noticed that many programmers use classes to store data about such things like: Class Customers .....Phone ....ID ....Address End Class....
2
1411
by: Paul | last post by:
I have a situation that I want to work but don't know the proper way to handle it. I want to create a User Defined "Type" (structure, class or enumeration). I'm not sure what it should be or where it should reside. I'll use Enum for this example. Currently in a Public Module: ---------------------------- Public Enum MyUserDefinedType
2
2411
by: thomasfarrow | last post by:
At work, our development team has a development standards document that insists Structures should never be used. I'm looking to change this standard but need a suitable argument in order to make the change. I know that Structures are value types, sit on the stack, and are generally more efficient to manipulate than reference types (i.e. Classes). Structures cannot use inheritance, the finalize method or default constructors. Can anyone...
3
1556
by: ArmsTom | last post by:
I was using structures to store information read from a file. That was working fine for me, but then I read that anything stored in a structure is added to the stack and not the heap. So, I made a class that stores the same information. The user selects any number of records from the file when the program loads & can then make changes. The records the user selects are added to an array and changes are made to the records in that array...
0
9683
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
10577
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10630
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,...
0
10275
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9407
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7005
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
5851
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4476
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4045
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.