Welcome!

Join our community of MMO enthusiasts and game developers! By registering, you'll gain access to discussions on the latest developments in MMO server files and collaborate with like-minded individuals. Join us today and unlock the potential of MMO server development!

Join Today!

C# Structs VS Classes

JavaScript Is Best Script
Joined
Dec 13, 2010
Messages
631
Reaction score
131
According to MSDN, "Each is essentially a data structure that encapsulates a set of data and behaviors that belong together as a logical unit. A class or struct declaration is like a blueprint that is used to create instances or objects at run time"

But what is the difference between a struct and a class? The main difference is that a struct is generally a value type while a class is generally a reference type. But what does this means anyway?

Class - Reference type :
Whenever you pass an instance of a class around, you are actually passing itself around, just as how you do in real life. For example, you create an apple and you want your dad to have it. You simply pass that apple to your dad. Whatever he does to the apple (eat it, paint it, slice it), the changes will be reflected directly on the apple you created. Pretty straight forward lets see some examples:
Code:
Apple myApple = new Apple(); // Assume we have a [B]class[/B] named "Apple"
myApple.sweetness = 0; // Sets a field to 0
Apple dadApple = myApple; // Passes my apple to dad
dadApple.sweetness += 2; // Adds 2 to the field of dad's apple, which is also my apple
Console.WriteLine(myApple.Sweetness + "," + dadApple.Sweetness); // Outputs "2,2"
So yeah, that's what a reference type is. Any changes is reflected upon the original object itself. Heres a declaration of a class:
Code:
    class Apple
    {
        public int sweetness; // a field in the struct
        
        public void ChopIntoHalf() // some method in the struct
        {
            this.sweetness /= 2;
        }
    }

Struct - Value type :
Whenever you pass an instance of a struct around, you are actually passing a copy of it around. What does this means, well it means for example, you create an apple A and you want to let your dad have possession of this apple. To do so, since your apple is a struct type, you would create an exact copy B of apple A and pass B to your dad. Whatever your dad does to the apple (eat it, paint it, slice it) will NOT affect apple A. That's what a struct is. Whenever you pass it around as a parameter, you are passing the VALUE of it, not the object itself. Any changes to the copy will NOT affect the original copy. Let's take an example :
Code:
Apple myApple = new Apple(); // Assume "Apple" is a struct
myApple.sweetness = 0; // sets a field to 0
Apple dadApple = myApple; // [B]Copies[/B] my apple and passes the copy to dad to make it his
dadApple.sweetness += 2; // Adds 2 to dad's apple, which is the [B]copy[/B] of my apple
Console.WriteLine(myApple.Sweetness + "," + dadApple.Sweetness); // Outputs "0,2"
As you can see, My apple doesn't get affected by the changes done to dad's apple, because i copied my apple initially and assigned this copy to dad to make it his. Therefore the apple dad has is merely a copy of mine. Here's an example of a struct:
Code:
    struct Apple
    {
        public int sweetness; // a field in the struct
        
        public void ChopIntoHalf() // some method in the struct
        {
            this.sweetness /= 2;
        }
    }
As you can see, its same as declaring a class. however it is important to note that some rules are different which i left out (damn).

So to sum things up a bit, a struct is a value type and it copies itself whenever it gets passed around. Classes on the other hand are reference types and they themselves (to be more specific : a pointer pointing to them) get passed around instead of copying themselves and passing their copies around.

So when do we use structs, when do we use classes?
Performance-wise, as you can see that structs make a copy of themselves whenever they are passed around, you generally do not, will not and shall not use structs for extremely large data types. Why? Lets say you have an instance of a struct that uses up 2 MB of memory. Whenever you pass it around your computer has to copy exactly these 2MB and pass this copy around. This means that 1) Your program will eat up a lot of memory, 2) Your program might take a bit long to copy this memory. Hence, Structs are used for small data types while classes for large(to be specific : more complex) data types.

Some examples of structs in the .NET Framework : byte, int, short, ushort, BigInteger, long, double
Some examples of classes in the .NET Framework : FileStream, Socket, TcpListener

You might have noticed in my first paragraph i said that classes are generally reference types. However there are exceptions, such as the string class which is a value type.

Well that's all for now. :D
 
Last edited:
JavaScript Is Best Script
Joined
Dec 13, 2010
Messages
631
Reaction score
131
I love your tutorials and I always learn from them.

Keep it up!

Thank you man :) Just request me to do a tutorial on a certain topic and i'll be glad to help you.
 
JavaScript Is Best Script
Joined
Dec 13, 2010
Messages
631
Reaction score
131
nice tut!
wanna expand it by showing source code of a example class and an example struct?
thats what some ppl will be interested in.

Thanks man, added the declarations in ^^ Though i left out some important notes about polymorphism, property declarations and constructor declarations...
 
• ♠️​ ♦️ ♣️ ​♥️ •
Joined
Mar 25, 2012
Messages
909
Reaction score
464
u failed at copy paste, both is struct now xD. and i would always use "this." as prefix if possible, better to understand for newbies at all.
the declarations are pretty similar in both versions, however u already made it. ^^
 
JavaScript Is Best Script
Joined
Dec 13, 2010
Messages
631
Reaction score
131
u failed at copy paste, both is struct now xD. and i would always use "this." as prefix if possible, better to understand for newbies at all.
the declarations are pretty similar in both versions, however u already made it. ^^

Woops, sorry did that in a rush, fixed now and added the this. Prefix ^^

2
 
JavaScript Is Best Script
Joined
Dec 13, 2010
Messages
631
Reaction score
131
Correct me, if I'm wrong, but you can also pass structs by reference, using the ref-keyword ;)

Yep, theres also the 'out' and 'in' keyword, but they'll have to be used explicitly to pass a struct by reference :D
 
Junior Spellweaver
Joined
Nov 28, 2006
Messages
114
Reaction score
3
Was looking for the difference a while ago, but you just nailed it in a fairly small post, thanks!
 
Initiate Mage
Joined
May 24, 2013
Messages
7
Reaction score
2
This is like asking in C++ 'when should I use pointers?' but its rather informative thanks
 
JavaScript Is Best Script
Joined
Dec 13, 2010
Messages
631
Reaction score
131
This is like asking in C++ 'when should I use pointers?' but its rather informative thanks

That is true!

However, classes in C++ are passed about by value while classes in C# are passed by reference generally. So whenever you pass an instance of a C# class about, you are actually passing points around.
 
Junior Spellweaver
Joined
Mar 15, 2009
Messages
151
Reaction score
51
Whenever you pass it around as a parameter, you are passing the VALUE of it, not the object itself.

Small nitpick, but it's the same for reference types. The value of a reference type is the reference itself. This is why reference types are 'pass-by-value' in C#, and not 'pass-by-reference', which is a different concept. To pass objects by value, you need to use the 'ref' keyword.
 
• ♠️​ ♦️ ♣️ ​♥️ •
Joined
Mar 25, 2012
Messages
909
Reaction score
464
Small nitpick, but it's the same for reference types. The value of a reference type is the reference itself. This is why reference types are 'pass-by-value' in C#, and not 'pass-by-reference', which is a different concept. To pass objects by value, you need to use the 'ref' keyword.

no. to pass variables as reference you use the ref keyword. It's the same usage as pointers.
 
Elite Diviner
Joined
May 30, 2011
Messages
443
Reaction score
95
Small nitpick, but it's the same for reference types. The value of a reference type is the reference itself. This is why reference types are 'pass-by-value' in C#, and not 'pass-by-reference', which is a different concept. To pass objects by value, you need to use the 'ref' keyword.

Oh, I want to nitpick too. Objects and references are slightly different in this context, but you used them interchangeably. So just to clarify: references to heap objects are passed by value (copied to the called function's stack), which means the underlying object's representation on the heap can be changed by functions they're passed to, but you can't change the object a parameter 'points' to on the heap. When you use the 'ref' keyword, it passes a reference by reference, so that the called function has the same reference as its caller rather than a copy of it. The only objects that can really be passed by value are value types (i.e. structs, primitives and managed pointers or references thsemselves).
 
Last edited:
Junior Spellweaver
Joined
Mar 15, 2009
Messages
151
Reaction score
51
no. to pass variables as reference you use the ref keyword. It's the same usage as pointers.

Yeah sorry, I meant 'by reference' in the last sentence. Sorry for the confusion!

Oh, I want to nitpick too. Objects and references are slightly different in this context, but you used them interchangeably. So just to clarify: references to heap objects are passed by value (copied to the called function's stack), which means the underlying object's representation on the heap can be changed by functions they're passed to, but you can't change the object a parameter 'points' to on the heap. When you use the 'ref' keyword, it passes a reference by reference, so that the called function has the same reference as its caller rather than a copy of it. The only objects that can really be passed by value are value types (i.e. structs, primitives and managed pointers or references thsemselves).

I know that. I was saying that the value of a reference-type object is a reference (to underlying data on the heap), so when you pass it around, you pass it around by-value. See also: .

I know what you mean though.

Attempting C++ analogy:
struct instances: UnderlyingData
class instances: UnderlyingData&

struct instances + ref: UnderlyingData& (more or less, C# allows the reference to be rebound, which is ref's main benefit)
class instances + ref: UnderlyingData&& (again, C# allows the outer reference to be rebound)
 
Back
Top