By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,573 Members | 938 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,573 IT Pros & Developers. It's quick & easy.

Structs vs. Classes

P: n/a
Dom
I'm really confused by the difference between a Struct and a Class?
Sometimes, I want just a group of fields to go together. A Class
without methods seems wrong, in that it carries too much overhead (I
think). A Struct seems more appropriate. At least it is what I would
have used in other languages. But since a Struct *can* hold methods,
I wander if I am saving anything. If not, why use it?

May 5 '07 #1
Share this Question
Share on Google+
29 Replies


P: n/a
Hi,
The main difference is that Classes are by reference, but the structs
are passed by value, like the String type.
So Classes are faster than Structures..

Bye,
Diego

May 5 '07 #2

P: n/a
Dom
Well, fine. But I have to ask, what is the proper use of a Struct?
Would I ever use it instead of a Class?

On May 5, 7:08 pm, Diego Jancic <jan...@gmail.comwrote:
Hi,
The main difference is that Classes are by reference, but the structs
are passed by value, like the String type.
So Classes are faster than Structures..

Bye,
Diego

May 5 '07 #3

P: n/a
Diego Jancic wrote:
Hi,
The main difference is that Classes are by reference, but the structs
are passed by value, like the String type.
So Classes are faster than Structures..
Eugh.
It depends on what you're doing. Think about why ints are passed by
value, as an extreme example.

Alun Harford
May 5 '07 #4

P: n/a
Dom wrote:
I'm really confused by the difference between a Struct and a Class?
Sometimes, I want just a group of fields to go together. A Class
without methods seems wrong, in that it carries too much overhead (I
think). A Struct seems more appropriate. At least it is what I would
have used in other languages. But since a Struct *can* hold methods,
I wander if I am saving anything. If not, why use it?
Structs is value types. Classes is reference types.

There are some different performance characteristics of
those, but it is a rather complex story.

If you go by the rule of using struct for bundling
data with no methods locally withing methods or at
least within assemblies and then use class for all
other, then you will be OK in 99% of cases.

And when you learn more about value types and
reference types, then you will really know.

Arne

May 6 '07 #5

P: n/a
Diego Jancic wrote:
The main difference is that Classes are by reference, but the structs
are passed by value, like the String type.
Both classes and structs are default passed by value and both
can be passed by reference. Passing a reference type bu value
and passing a value type by reference is not the same.
So Classes are faster than Structures..
Sometimes. Definitely not always.

Arne
May 6 '07 #6

P: n/a
Dom
On May 5, 8:25 pm, Arne Vajhj <a...@vajhoej.dkwrote:
Both classes and structs are default passed by value
Are you sure about this? From MS help: "When passing a struct to a
method, it is passed by value instead of as a reference."

I think the implication is that classes are passed by reference.


May 6 '07 #7

P: n/a
Dom wrote:
On May 5, 8:25 pm, Arne Vajhj <a...@vajhoej.dkwrote:
>Both classes and structs are default passed by value

Are you sure about this?
112%
From MS help: "When passing a struct to a
method, it is passed by value instead of as a reference."

I think the implication is that classes are passed by reference.
No.

http://msdn2.microsoft.com/en-us/lib...28(VS.80).aspx

Arne

May 6 '07 #8

P: n/a
Dom
I think the implication is that classes are passed by reference.

No.

http://msdn2.microsoft.com/en-us/lib...28(VS.80).aspx

Arne
Then I'm confused by this from MS help: "This example shows that when
a struct is passed to a method, a copy of the struct is passed, but
when a class instance is passed, a reference is passed."

Maybe it's a question of semantics. Your saying that the variable
itself is passed by value. The example shows that this variable can
not be made to point to a new object, except locally. But the
important point is that (I think) when you pass a struct, the entire
struct is placed on the call stack. If the struct is 5 long words,
then all 5 long words are there. When you pass an object, the single
reference is placed on the call stack, not all the fields. Your point
is just that a copy of the reference is placed there.
May 6 '07 #9

P: n/a
Dom wrote:
>>I think the implication is that classes are passed by reference.
No.

http://msdn2.microsoft.com/en-us/lib...28(VS.80).aspx

Then I'm confused by this from MS help: "This example shows that when
a struct is passed to a method, a copy of the struct is passed, but
when a class instance is passed, a reference is passed."

Maybe it's a question of semantics. Your saying that the variable
itself is passed by value. The example shows that this variable can
not be made to point to a new object, except locally. But the
important point is that (I think) when you pass a struct, the entire
struct is placed on the call stack. If the struct is 5 long words,
then all 5 long words are there. When you pass an object, the single
reference is placed on the call stack, not all the fields. Your point
is just that a copy of the reference is placed there.
Exactly.

Arne

May 6 '07 #10

P: n/a
The main difference between class and struct are as follows:

a) Classes are created on heap while structs are created on stack.
b) Classes are passed by reference (by default) while structs are passed by
value.
v) Structs does not support inheritance.

Having said these differences, I belive structs is nothing but a data
structure that is exchanged and manipulated by various application elements
but structs itself does not have have any behaviour. I know structs could
have method/ functions but theoritically speaking, structs should "NOT" have
any behavior rather it is a data structure that holds data and is manipulated
by various classes.

--
Tariq Karim | Capgemini | El-Segundo
Senior Consultant | Telecom Media and Entertainment
Mobile: +01 832-433-6055 | www.capgemini.com
Join the Collaborative Business Experience

"Arne Vajhøj" wrote:
Dom wrote:
I'm really confused by the difference between a Struct and a Class?
Sometimes, I want just a group of fields to go together. A Class
without methods seems wrong, in that it carries too much overhead (I
think). A Struct seems more appropriate. At least it is what I would
have used in other languages. But since a Struct *can* hold methods,
I wander if I am saving anything. If not, why use it?

Structs is value types. Classes is reference types.

There are some different performance characteristics of
those, but it is a rather complex story.

If you go by the rule of using struct for bundling
data with no methods locally withing methods or at
least within assemblies and then use class for all
other, then you will be OK in 99% of cases.

And when you learn more about value types and
reference types, then you will really know.

Arne

May 6 '07 #11

P: n/a
Dom,

In my experience, in .NET, most of the time when I start out with a
struct I end up changing it to a class because it ends up needing to use
inheritance or in some other way evolves into something that's more
appropriately represented as a class. IIRC there can also be versioning
issues if you expose a struct publicly and then need to change it to a
class later.

In most real-world line of business app development, there is so little
overhead savings with structs that it's probably fine to default to
classes unless you stumble onto a compelling need for a struct. I
seldom see them in other people's code, either.

If you are implementing something that will be using value semantics,
that's one thing, but most of what is useful in that regard is built
into the CLR already. I don't see structs as something that's commonly
going to be used in everyday line of business development. Unless
you're doing something really demanding like manipulating huge matrices
or some kinds of game development for instance, the question of structs
vs classes is not something you need to expend bandwidth on.

--Bob

Dom wrote:
I'm really confused by the difference between a Struct and a Class?
Sometimes, I want just a group of fields to go together. A Class
without methods seems wrong, in that it carries too much overhead (I
think). A Struct seems more appropriate. At least it is what I would
have used in other languages. But since a Struct *can* hold methods,
I wander if I am saving anything. If not, why use it?
May 6 '07 #12

P: n/a
On Sat, 05 May 2007 17:30:58 -0700, Dom <do********@gmail.comwrote:
On May 5, 8:25 pm, Arne Vajhøj <a...@vajhoej.dkwrote:
>Both classes and structs are default passed by value

Are you sure about this? From MS help: "When passing a struct to a
method, it is passed by value instead of as a reference."

I think the implication is that classes are passed by reference.
There's "reference", and then there's "reference". Clear? :)

What Arne is saying is that the parameter passing method of both classes
and structs is "by value". *BUT* (and this is a pretty big "but"),
because the "value" of a class is always a reference, they are in another
sense of the word always passed by reference.

In C++, you can instantiate a class on the stack, or as a global, but in
C# all classes are always allocated from the heap and they are always
referred to by a reference to the instance. So in that sense, you are
correct that they are passed via that reference.

But in terms of the definition of "passing by reference", they are not
passed by reference. The reference to the class is passed, yes...but that
reference is passed "by value". If it were passed "by reference", then
the variable holding the reference itself could be changed (and that is
the case when the "ref" or "out" keyword is used).

Structs, on the other hand, being "value" types always need a place to
keep them, and aren't referred to by reference. So when you pass a struct
"by value", the whole struct is passed.

IMHO, this all is one of the more confusion areas of C#, especially
because you still need to use the "new" keyword to initialize a struct.
It makes it look like you are creating a new instance, just as happens
with a class, and assigning the reference to that instance to (for
example) a local variable. But that's not what happens. The storage for
your struct is represented by that local variable itself, not a reference
to a newly allocated place in memory.

I'm fine with the behaviors of structs and classes being different (even
though in C++ they are practically the same), but IMHO it was a mistake to
keep the syntax of the two the same as well. It only leads to confusion.

Pete
May 6 '07 #13

P: n/a
Dom <do********@gmail.comwrote:
On May 5, 8:25 pm, Arne Vajhj <a...@vajhoej.dkwrote:
Both classes and structs are default passed by value
Are you sure about this? From MS help: "When passing a struct to a
method, it is passed by value instead of as a reference."

I think the implication is that classes are passed by reference.
No, they're passed *as* a reference. That reference is passed by value
by default.

See http://pobox.com/~skeet/csharp/parameters.html for more
information.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 6 '07 #14

P: n/a
Dom <do********@gmail.comwrote:
Then I'm confused by this from MS help: "This example shows that when
a struct is passed to a method, a copy of the struct is passed, but
when a class instance is passed, a reference is passed."
Yes - a reference is passed. That's not the same as "passing the object
by reference."
Maybe it's a question of semantics. Your saying that the variable
itself is passed by value. The example shows that this variable can
not be made to point to a new object, except locally. But the
important point is that (I think) when you pass a struct, the entire
struct is placed on the call stack. If the struct is 5 long words,
then all 5 long words are there. When you pass an object, the single
reference is placed on the call stack, not all the fields. Your point
is just that a copy of the reference is placed there.
Exactly - because the value of the variable (or other reference type
expression) isn't the object itself, it's just a reference.

In both the struct and the class case, the value of the expression is
passed by value: the expression is evaluated, and the value of the
expression is copied as the initial value of the parameter within the
called method.

Passing by reference is subtly different - see the page I referenced in
my other post for more details.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 6 '07 #15

P: n/a
Peter Duniho <Np*********@nnowslpianmk.comwrote:

<snip>
I'm fine with the behaviors of structs and classes being different (even
though in C++ they are practically the same), but IMHO it was a mistake to
keep the syntax of the two the same as well. It only leads to confusion.
I think it's a problem which will diminish over time, leaving the
benefit of consistency of how you create new instances of a type,
whether they're reference or value types.

I believe most of the confusion is for migrating C++ programmers, who
are used to "new" *always* creating a new object on the heap.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 6 '07 #16

P: n/a
Tariq Karim <Ta********@discussions.microsoft.comwrote:
The main difference between class and struct are as follows:

a) Classes are created on heap while structs are created on stack.
Class instances are indeed always created on the heap, at least with
C#, with the exception of fixed arrays which can be created on the
stack in unsafe code.

However, value type instances are *often* on the heap - as part of
other instances. If I do:

class Foo
{
int i;
}

Foo f = new Foo();

The object referred to by f is on the heap, including its "i" member.
See http://pobox.com/~skeet/csharp/memory.html for more on this.
b) Classes are passed by reference (by default) while structs are passed by
value.
No. See http://pobox.com/~skeet/csharp/parameters.html
v) Structs does not support inheritance.
They support interface inheritance, but not implementation inheritance.
Having said these differences, I belive structs is nothing but a data
structure that is exchanged and manipulated by various application elements
but structs itself does not have have any behaviour.
No...
I know structs could have method/ functions but theoritically
speaking, structs should "NOT" have any behavior rather it is a data
structure that holds data and is manipulated by various classes.
Just because they don't have behaviour in *some* languages doesn't mean
they shouldn't have behaviour in C# or .NET. Why should something being
a value type mean that it shouldn't have behaviour? Would you rather
DateTime didn't have any methods in it? That you couldn't use
int.ToString()?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 6 '07 #17

P: n/a
Dom <do********@gmail.comwrote:
I'm really confused by the difference between a Struct and a Class?
Sometimes, I want just a group of fields to go together. A Class
without methods seems wrong, in that it carries too much overhead (I
think). A Struct seems more appropriate. At least it is what I would
have used in other languages. But since a Struct *can* hold methods,
I wander if I am saving anything. If not, why use it?
See http://pobox.com/~skeet/csharp/references.html
It's still a work in progress, but hopefully it'll give you the gist of
it.

Don't be concerned about the overhead of making something a class -
just consider whether you really want a value type or a reference type.
As a rule of thumb, it's pretty rare to create a new value type in your
own code, although of course you'll be *using* value types (like int)
all the time.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 6 '07 #18

P: n/a
On May 5, 7:46 pm, Tariq Karim <TariqKa...@discussions.microsoft.com>
wrote:
The main difference between class and struct are as follows:

a) Classes are created on heap while structs are created on stack.
b) Classes are passed by reference (by default) while structs are passed by
value.
v) Structs does not support inheritance.

Having said these differences, I belive structs is nothing but a data
structure that is exchanged and manipulated by various application elements
but structs itself does not have have any behaviour. I know structs could
have method/ functions but theoritically speaking, structs should "NOT" have
any behavior rather it is a data structure that holds data and is manipulated
by various classes.
Sorry, IMHO this is dead wrong.

Here are what I would consider better guidelines for choosing between
struct and class.

Use struct when you want a value type; use class in all other cases.
(There is one caveat... I'll get to that in a moment.)

So... when do you need a value type? When you need something that
would act like an int or a double or a DateTime: when you manipulate
it, you create a new one; they are immutable (once you create one you
can't change it); an instance of one has no identity. Let me expand on
those one by one.

First, when you manipulate an integer... say you negate it... you
don't actually change the integer itself. When you change 5 into -5
you do not change every 5 in your program into a -5. Instead, you
manipulate the value 5, get -5 as the result, and assign that result
to some variable (or back into the same variable that held the 5).
Every operation on a typical value type creates a new value.

This goes hand in glove with the "rule" that values are immutable.
It's sort of an odd concept to change a value "in place": usually you
do some operation to get a new value and then replace the old value
with the new one. There are exceptions in the .NET Framework (they're
the "caveat"... coming up shortly) but usually value types are
immutable.

The identity thing is an interesting angle that I dreamed up a while
back. If the thing you're creating has a UID, or could have a UID,
then it's a lousy candidate for a value type. You can't talk about
"this value 5" versus "that value 5" 5 is 5, and each copy of the
value 5 has nothing to distinguish it from the others. This is
different from "Bob Smith, customer #1234". In particular, it makes
sense to change some attribute of this customer #1234 and have every
reference to that customer in your entire program see that change. You
can't do that with value types. If you have more than one copy of a
reference type... more than one copy of customer #1234, then it's
usually something you've done deliberately: you have the "updated
customer #1234" versus the "original customer #1234" or something like
that. One doesn't expect to see objects with identities copied will-ye-
nil-ye all over your program, whereas with value types this is normal.

This is why I consider Tariq's advice to be dead wrong. If you make,
say, a customer record a value type, even though it may contain no
methods only fields, this will result in major frustration. The
problem is that a customer is usually something that you want to be
able to change and, when you do, you want all of the references to
that customer all over your program to see that change. Or, if you
want some of them to change but not others, then it's usually
something quite deliberate over which you want full control. If you
make it a value type, you'll change the one copy you're storing, and
if you want any other copies to see the change, you'll have to assign
the changed copy explicitly. In effect, you can end up with hundreds
of copies of "customer #1234" without really trying, and keeping those
copies in synch will be a nightmare. Very, very ugly.

And now, the caveat. In a few extreme situations, the .NET Framework
has chosen to make unlikely value types. Point and Rectangle come to
mind, but there are more. They are, unfortunately, mutable, more for
convenience of notation than for any other reason. These are the few
cases in which the Framework designers chose to make something a value
type for efficiency reasons, not necessarily because value semantics
were the logical choice (although making them values does change their
semantics). The efficiency gained here is that making these small
objects values eliminates the cost of allocating zillions of them on
the heap and then having to garbage collect them. In effect, Points
and Rectangles are used in calculations, or the designers expected
them to be used in calculations, and they didn't want intermediate
results to be allocated on the heap and therefore incur GC overhead to
clean them up.

The semantics do change, though: a Point value type is conceptually
different from a Point reference type, but that's fodder for another
post.

As far as value types having methods, absolutely they can, and most
likely will. I'll close with a common example to illustrate what I
mean.

I created a value type called Measure: it consists of a quantity and a
unit of measure, and it's used to represent things like "12 inches" or
"15 kilograms". That sort of thing. My Measure value type has all
sorts of methods. In addition to the usual overloads for arithmetic
operators, there are methods like this:

decimal kiloQuantity = productWeight.GetValueAs(UnitOfMeasure.Kilos);

or

UnitOfMeasure native = productWeight.NativeUnitOfMeasure;

The reason it's a value type is _not_ that it's somehow "lightweight"
or that it doesn't have any methods. It's a value type because I want
it to act like a value.

If you're familiar with C++, then you can think of it like this. In C+
+, "struct" and "class" mean almost the same thing. Whether it's a
value (stored on the heap, copied on assignment, etc) is something you
decide every time you create an object or assign it. In C++ you decide
over and over again, at each turn, whether you want something to act
like a value or like a reference type. For example, if you say

MyType foo;

in C++, then any new instance of MyType is copied into "foo" and
stored on the stack. If you say instead

MyType *foo;

then any new instance of MyType is referenced by "foo" and could be
stored anywhere (but most often on the heap). If you were to pass a
MyType to a method, you decide whether you want to pass a value or a
reference by the method signature: a * means pass a reference, no *
means pass a value.

In C# you decide these things once and for good up front. If you
declare something a struct, then it is allocated in-place and passed
by value (unless you specify the "ref" keyword explicitly). If you
declare something a class, then it is allocated on the heap and
references to it are passed about. If you want a copy, you have to
explicitly .Clone() it.

Which one you choose _normally_ does not hinge on efficiency concerns,
but how you want the thing to _act_, and 99% of the time you want
things to act like reference types, in my experience.

May 6 '07 #19

P: n/a
On Sat, 05 May 2007 23:34:33 -0700, Jon Skeet [C# MVP] <sk***@pobox.com>
wrote:
Peter Duniho <Np*********@nnowslpianmk.comwrote:

<snip>
>I'm fine with the behaviors of structs and classes being different (even
though in C++ they are practically the same), but IMHO it was a mistake
to
keep the syntax of the two the same as well. It only leads to
confusion.

I think it's a problem which will diminish over time, leaving the
benefit of consistency of how you create new instances of a type,
whether they're reference or value types.

I believe most of the confusion is for migrating C++ programmers, who
are used to "new" *always* creating a new object on the heap.
Possibly. And yet a) most C# programmers, at least for the near future,
will in fact be C++ programmers migrating, and b) even if we reach a point
where most C# programmers are indeed ones who started out with C# and thus
have been indoctrinated in the languages subtle quirks, that does not in
my mind change the fact that having a "new" operator do two very different
things depending on the type of object on which it's operating is just not
a great idea.

Note that, at least in my view, there *isn't* consistency of how you
create new instances of a type. When you use the "new" operator with a
struct, you aren't really creating a new instance of that type. The new
instance of a struct is created when the containing object is created
(whether that's on the stack, or in a class, or another struct). The
"new" operator doesn't really create the instance that you're using.

So I'm not really on board with respect to your thought that over time,
we'll be left with "the benefit of consistency of how you create new
instances of a type". I don't see that consistency today, and so don't
see that we'll be left with that in the future.

It's a classic example of inappropriate operator overloading, IMHO. It
falls in with other C#/.NET "features", such as the use of the word
"event" to describe something very different from a "WaitableEvent", as
well as the use of the method name "Invoke()" to describe one thing in the
Form class, and something somewhat different on a delegate.

It's certainly not a big deal...any person spending any significant amount
of time with C# can easily get accustomed to these issues. But they do
detract from the general theme of C# and .NET of trying to avoid apparent
ambiguity.

Pete
May 6 '07 #20

P: n/a
Peter Duniho <Np*********@nnowslpianmk.comwrote:
I think it's a problem which will diminish over time, leaving the
benefit of consistency of how you create new instances of a type,
whether they're reference or value types.

I believe most of the confusion is for migrating C++ programmers, who
are used to "new" *always* creating a new object on the heap.

Possibly. And yet a) most C# programmers, at least for the near future,
will in fact be C++ programmers migrating
I think I'd need to see some numbers before I believe that. I reckon VB
and Java programmers form a large proportion too - possibly larger than
C++ programmers.
and b) even if we reach a point
where most C# programmers are indeed ones who started out with C# and thus
have been indoctrinated in the languages subtle quirks, that does not in
my mind change the fact that having a "new" operator do two very different
things depending on the type of object on which it's operating is just not
a great idea.
Well, it does the same thing in some ways, and different things in
other ways. It does the "same thing" in the same way that both value
types and reference types are passed by value by default - if you
understand that the difference between reference types and value types,
it makes sense, although if you don't, it doesn't.
Note that, at least in my view, there *isn't* consistency of how you
create new instances of a type. When you use the "new" operator with a
struct, you aren't really creating a new instance of that type. The new
instance of a struct is created when the containing object is created
(whether that's on the stack, or in a class, or another struct). The
"new" operator doesn't really create the instance that you're using.
I think it depends on exactly what one means by "instance", to be
honest. I nearly used the word "value" but thought that wouldn't be
clear. It's quite possible that we don't have adequate terminology at
the moment.

(Just to be clear, I'm sure we agree on what actually happens, just not
on what we call it.)
So I'm not really on board with respect to your thought that over time,
we'll be left with "the benefit of consistency of how you create new
instances of a type". I don't see that consistency today, and so don't
see that we'll be left with that in the future.
I suspect we'll have to agree to disagree on this, but I'm fine with
that.
It's a classic example of inappropriate operator overloading, IMHO. It
falls in with other C#/.NET "features", such as the use of the word
"event" to describe something very different from a "WaitableEvent", as
well as the use of the method name "Invoke()" to describe one thing in the
Form class, and something somewhat different on a delegate.
Yes - I've just been writing about delegates and trying to write
coherently about Control.Invoke vs Delegate.Invoke. It's insanely
difficult to make it readable.
It's certainly not a big deal...any person spending any significant amount
of time with C# can easily get accustomed to these issues. But they do
detract from the general theme of C# and .NET of trying to avoid apparent
ambiguity.
Whereas I quite like not having to have two different types of syntax
for calling constructors.

Out of interest, what would you propose for calling a value type
constructor? (Please not the C++ syntax!)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 6 '07 #21

P: n/a
On Sun, 06 May 2007 02:18:34 -0700, Jon Skeet [C# MVP] <sk***@pobox.com>
wrote:
>[...] that does not in
my mind change the fact that having a "new" operator do two very
different things depending on the type of object on which it's
operating is just not a great idea.

Well, it does the same thing in some ways, and different things in
other ways. It does the "same thing" in the same way that both value
types and reference types are passed by value by default
Yes, that's sort of true. And it does the "same thing" in the same way
that "Control.Invoke" and "Delegate.Invoke" do the "same thing". My point
is that in the case of the "new" operator and the "Invoke" method, the
"same thing" is different enough that using the same syntax obscures some
fundamental differences in what's actually happening.

(For the record, the parameter passing aspect doesn't bother me at all,
because I think one thing that C# does make clear is the difference
between representation of value types and reference types).
- if you
understand that the difference between reference types and value types,
it makes sense, although if you don't, it doesn't.
Well, I *think* I understand the difference, and yet to me it doesn't make
sense to have to call "new" on a value type.
>[...] The
"new" operator doesn't really create the instance that you're using.

I think it depends on exactly what one means by "instance", to be
honest. I nearly used the word "value" but thought that wouldn't be
clear. It's quite possible that we don't have adequate terminology at
the moment.
Maybe. To me, "instance" means the actual storage required by the
variable. There's a physical, real-world connection between an "instance"
and the place where that "instance" is stored. But with value types in
C#, by the time I get around to writing "ValueType variable = new
ValueType()", the storage has been allocated and all that "new" is doing
for me is initializing that storage.
I suspect we'll have to agree to disagree on this, but I'm fine with
that.
Me too. After all, it doesn't change how we use the language. I just
feel it's more confusion to new C# programmers than it needs to be. (And
personally, being a new C# programmer I feel that I have a better handler
on what's confusing and what's not than some of you more experienced C#
folks :) ).
[...]
Whereas I quite like not having to have two different types of syntax
for calling constructors.

Out of interest, what would you propose for calling a value type
constructor? (Please not the C++ syntax!)
Off the top of my head, I don't know. There's a reason I'm not a language
designer. :) All I know is that this code:

ValueType valuevar = new ValueType();
RefType refvar = new RefType();

has two lines that look like they do the same thing, and yet they don't do
the same thing at all.

If there were some way to get a reference to a value type that took
advantage of the "new" syntax, maybe it wouldn't bug me so much.
Something related to boxing, for example. But as far as I know, there
isn't. Feel free to correct me if I'm wrong about that. :)

Pete
May 6 '07 #22

P: n/a
Peter Duniho <Np*********@nnowslpianmk.comwrote:
Well, it does the same thing in some ways, and different things in
other ways. It does the "same thing" in the same way that both value
types and reference types are passed by value by default

Yes, that's sort of true. And it does the "same thing" in the same way
that "Control.Invoke" and "Delegate.Invoke" do the "same thing". My point
is that in the case of the "new" operator and the "Invoke" method, the
"same thing" is different enough that using the same syntax obscures some
fundamental differences in what's actually happening.
I'd say they're more similar than that - but it's the kind of thing
which wouldn't do much good to debate.
(For the record, the parameter passing aspect doesn't bother me at all,
because I think one thing that C# does make clear is the difference
between representation of value types and reference types).
Shame it's something that gets a lot of people confused :(
- if you
understand that the difference between reference types and value types,
it makes sense, although if you don't, it doesn't.

Well, I *think* I understand the difference, and yet to me it doesn't make
sense to have to call "new" on a value type.
For me it creates a new "value" - but there we go.
[...] The
"new" operator doesn't really create the instance that you're using.
I think it depends on exactly what one means by "instance", to be
honest. I nearly used the word "value" but thought that wouldn't be
clear. It's quite possible that we don't have adequate terminology at
the moment.

Maybe. To me, "instance" means the actual storage required by the
variable. There's a physical, real-world connection between an "instance"
and the place where that "instance" is stored. But with value types in
C#, by the time I get around to writing "ValueType variable = new
ValueType()", the storage has been allocated and all that "new" is doing
for me is initializing that storage.
You see, to me, an instance is a collection of variable values. The
storage doesn't particularly bother me. Therefore even if I've already
got a value, with my way of looking at things I'm creating a new
instance which is replacing the old instance - whereas of course with
your way of of looking at it I quite see that you're just replacing the
data within the existing instance.
I suspect we'll have to agree to disagree on this, but I'm fine with
that.

Me too. After all, it doesn't change how we use the language. I just
feel it's more confusion to new C# programmers than it needs to be. (And
personally, being a new C# programmer I feel that I have a better handler
on what's confusing and what's not than some of you more experienced C#
folks :) ).
That would certainly be true if I hadn't helped rather a lot of other
newbie C# people over time (not trying to be immodest, just honest) -
and I think you have *much* more experience of other languages than
most of the C# neophytes I've seen, to be honest. I expect to be able
to explain things to you (on the rare occasions where it's necessary,
frankly) in terms which are defined elsewhere, point you at those
definitions and let you get on with it - rather than doing a lot of
hand-holding, comparing with real-world examples etc.

This is in no way to diminish the importance of the things you find
irritating/tricky/confusing/whatever.
Out of interest, what would you propose for calling a value type
constructor? (Please not the C++ syntax!)

Off the top of my head, I don't know. There's a reason I'm not a language
designer. :) All I know is that this code:

ValueType valuevar = new ValueType();
RefType refvar = new RefType();

has two lines that look like they do the same thing, and yet they don't do
the same thing at all.
Wise words from Obi wan: "Luke, you're going to find that many of the
truths we cling to depend greatly on our own point of view."

:)

They're certainly different in terms of whether they need to allocate
storage or not. If you see the major point as being initializing an
instance, and use my view of an instance, it's a different story :)
(I'm not going to claim the differences go away, just that I'd disagree
with the claim that "they don't do the same thing at all".)
If there were some way to get a reference to a value type that took
advantage of the "new" syntax, maybe it wouldn't bug me so much.
Something related to boxing, for example. But as far as I know, there
isn't. Feel free to correct me if I'm wrong about that. :)
Well, this would do it:
object o = new ValueType();

but it's really not what you want, most of the time ;)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
May 6 '07 #23

P: n/a
On Sun, 06 May 2007 11:31:41 -0700, Jon Skeet [C# MVP] <sk***@pobox.com>
wrote:
[...]
>If there were some way to get a reference to a value type that took
advantage of the "new" syntax, maybe it wouldn't bug me so much.
Something related to boxing, for example. But as far as I know, there
isn't. Feel free to correct me if I'm wrong about that. :)

Well, this would do it:
object o = new ValueType();

but it's really not what you want, most of the time ;)
Yeah, no...I wasn't really looking to box the value type per se. Just
something *like* that. :)

Though, I suppose in the context of C# that's going to accomplish almost
the same thing.

Anyway, thanks for the comments...I do see where you're coming from, and
mostly I'm of the mind that since the language is the way it is, how I
wish it to be isn't nearly as relevant as how it is today. Even if I'm
not entirely satisfied, I'm glad that the language does at least make
sense to someone, as that shows that the design isn't arbitrarily wrong or
anything like that.

And that's a good thing. :)

Pete
May 7 '07 #24

P: n/a
Diego Jancic wrote:
So Classes are faster than Structures..
In my FFT, using structs for complex numbers instead of classes is 3x
faster.

--
Dr Jon D Harrop, Flying Frog Consultancy
The F#.NET Journal
http://www.ffconsultancy.com/product...ournal/?usenet
May 7 '07 #25

P: n/a
On May 6, 5:26 pm, Jon Harrop <j...@ffconsultancy.comwrote:
Diego Jancic wrote:
So Classes are faster than Structures..

In my FFT, using structs for complex numbers instead of classes is 3x
faster.
Yes, of course... complex numbers are natural value types.
Particularly if you do a lot of calculations that involve intermediate
results, structs will be much quicker because they don't have to be
allocated on the heap, and they don't have to be GC'd.

On the other hand, if you make something large like a customer record
a struct, then it will be copied on every assignment and every time
it's passed to a method (unless you use "ref"), which eats up
substantial amounts of time and memory. Not to mention the horrible
mess that results as you try to fashion your code to _avoid_ having
the thing be copied all over the place.

The moral: use the appropriate tool for the job. Classes are a lousy
representation for complex numbers. Structs are a lousy representation
for customers, stock items, etc.

By the way, Mr. Harrop, I take it this means that you've managed to
sort out the complex number thing in C#. Glad to hear it. :-)

May 7 '07 #26

P: n/a
"Dom" <do********@gmail.comschrieb im Newsbeitrag
news:11**********************@p77g2000hsh.googlegr oups.com...
Well, fine. But I have to ask, what is the proper use of a Struct?
structs is for simple, small, fixedsize types with value semantic, like the
predefined number types or things like DateTime etc.
Also string has value-semantic, but since it can have sice up to 4GiB it is
implemented as class.
Would I ever use it instead of a Class?
Very probably, never!

Christof
May 7 '07 #27

P: n/a
Bruce Wood wrote:
On May 6, 5:26 pm, Jon Harrop <j...@ffconsultancy.comwrote:
>Diego Jancic wrote:
So Classes are faster than Structures..

In my FFT, using structs for complex numbers instead of classes is 3x
faster.

Yes, of course... complex numbers are natural value types.
Particularly if you do a lot of calculations that involve intermediate
results, structs will be much quicker because they don't have to be
allocated on the heap, and they don't have to be GC'd.
Yes and no. I do not yet understand why but switching between struct and
class for my low-dimensional vectors (2D and 3D) shows that classes are
slightly faster in that case, yet I would have expected their use to be
very similar to that of a complex number.
The moral: use the appropriate tool for the job. Classes are a lousy
representation for complex numbers. Structs are a lousy representation
for customers, stock items, etc.
Absolutely. Judging by the semantics, I'd always opt for a class by default
and only try a struct if it could work and might be faster, i.e. avoid
premature optimization.
By the way, Mr. Harrop, I take it this means that you've managed to
sort out the complex number thing in C#. Glad to hear it. :-)
I had actually already written the whole thing when I posted that. I just
had the impression of reinventing the wheel by writing my own Complex
class...

--
Dr Jon D Harrop, Flying Frog Consultancy
The F#.NET Journal
http://www.ffconsultancy.com/product...ournal/?usenet
May 7 '07 #28

P: n/a
On May 7, 2:40 pm, Jon Harrop <j...@ffconsultancy.comwrote:
Bruce Wood wrote:
On May 6, 5:26 pm, Jon Harrop <j...@ffconsultancy.comwrote:
Diego Jancic wrote:
So Classes are faster than Structures..
In my FFT, using structs for complex numbers instead of classes is 3x
faster.
Yes, of course... complex numbers are natural value types.
Particularly if you do a lot of calculations that involve intermediate
results, structs will be much quicker because they don't have to be
allocated on the heap, and they don't have to be GC'd.

Yes and no. I do not yet understand why but switching between struct and
class for my low-dimensional vectors (2D and 3D) shows that classes are
slightly faster in that case, yet I would have expected their use to be
very similar to that of a complex number.
The moral: use the appropriate tool for the job. Classes are a lousy
representation for complex numbers. Structs are a lousy representation
for customers, stock items, etc.

Absolutely. Judging by the semantics, I'd always opt for a class by default
and only try a struct if it could work and might be faster, i.e. avoid
premature optimization.
Although I might be out of line given the domain you're working in, I
worry when people talk of struct versus class in terms of
"optimization". True, MS itself chose to go that route with Point and
Rectangle, but the most important thing for me is the change in
semantics between the two. The best example I have is that of a fellow
who posted here some time ago. He was trying to make a vector-based
graphics sketching program, and was frustrated that he couldn't seem
to get it to work with the already-available System.Drawing.Point
type.

The problem, of course, is that System.Drawing.Point is a struct.
This, in effect, makes it a commodity item, like int or double. You
make points, perform calculations that yield new points, and toss them
away when you're done with them. Points, ints, and doubles have very
low status within your program: you barely think about them, just make
new ones, copy them, transform them, and toss them. In particular (and
this was the fellow's problem) if you have two Point variables
containing (5, 5) and (5, 5), then there is no way to distinguish
them. That is to say, if the user drags a point from (4, 1) to (5, 5),
over top of another point already at (5, 5), then there's no way to
tell the two apart: value types have no identifying features apart
from their value.

What he wanted was a class. If you wrap System.Drawing.Point in a
class (or make your own class with x, y fields) then suddenly it
_does_ make sense to talk about "this point (5, 5)" versus "that point
(5, 5)", because a class has not only its state (aka value), but also
an address on the heap where it lives, so two points at (5, 5) _are_
distinguishable because they are stored in separate class instances.
Making these Point classes mutable causes no confusion, because that's
what we expect form reference semantics: if an object changes, all
references to that object see the change. It's all quite natural.

Changing from struct to class, or vice versa, dramatically changes how
the thing acts, and how you use it (or not). Of course, sometimes you
live with poor semantics because the difference in efficiency is
dramatic, but for the most type I decide between class and struct
based on how I want the thing to act.

May 7 '07 #29

P: n/a
Bruce Wood wrote:
Although I might be out of line given the domain you're working in, I
worry when people talk of struct versus class in terms of
"optimization". True, MS itself chose to go that route with Point and
Rectangle, but the most important thing for me is the change in
semantics between the two.
Alas, I don't think there is any difference in semantics between the two for
me as I'm writing in F# (well, apart from that FFT ;-).

As a functional language, F# passes everything by reference so the only
effect of using a struct is to unbox the data structure which might be
faster. Uniformity certainly makes life easier...

--
Dr Jon D Harrop, Flying Frog Consultancy
The F#.NET Journal
http://www.ffconsultancy.com/product...ournal/?usenet
May 8 '07 #30

This discussion thread is closed

Replies have been disabled for this discussion.