C# Why structure take less memory compare to class

T.Zacks 3,996 Reputation points
2022-09-13T17:04:13.69+00:00

Looking for list of points for which structure take less memory compare to class. i have checked these links
https://social.msdn.microsoft.com/Forums/vstudio/en-US/ff7fbffc-c6d3-474d-ad2c-8a2415852c00/why-they-say-struct-takes-lesser-memory-than-class-objects?forum=csharpgeneral

https://stackoverflow.com/questions/2761742/overhead-of-class-vs-structure-in-c
http://clarkkromenaker.com/post/csharp-structs/

another question is what is default in c# By Value or By Reference?
if by reference then how could i prove it just running a sample code. please share a sample code. thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,400 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 74,146 Reputation points
    2022-09-13T17:22:50.66+00:00

    C# structs are allocated on the stack unless "boxed". when "boxed" they are copied to the heap and must be garbage collected like a class instance. also as they do not implement inheritance, the methods do not require a vtable.

    the C# default is pass by value. to pass by ref, you use the ref key word

    using System;    
        
    int i = 0;    
        
    callbyvalue(i);    
    Console.WriteLine(i); // 0    
        
    callbyref(ref i);    
    Console.WriteLine(i); // 2    
        
    void callbyvalue(int x)    
    {    
     x = 1;    
    }    
        
    void callbyref(ref int x)    
    {    
     x = 2;    
    }    
        
    
     
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.