Re: Structs vs. Classes
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Sun, 6 May 2007 07:38:35 +0100
Tariq Karim <TariqKarim@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
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 - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
.
- References:
- Structs vs. Classes
- From: Dom
- Re: Structs vs. Classes
- From: Arne Vajhøj
- Structs vs. Classes
- Prev by Date: Re: Structs vs. Classes
- Next by Date: Re: Structs vs. Classes
- Previous by thread: Re: Structs vs. Classes
- Next by thread: Re: Structs vs. Classes
- Index(es):
Relevant Pages
|