-->
معلومات كل ساعه معلومات كل ساعه
recent

معلومات تهمك

recent
recent
جاري التحميل ...
recent

Value types & reference types



Value types & reference types

In C#, types have been divided into 2 parts, value types and the reference types. The value types directly store the data in the stack portion of RAM whereas the reference type stores reference of the data in the stack and save the actual data in heap but this is a half-truth statement. I will explain about it later to prove why it’s half-truth.


Value types


A value type contains its data directly and it is stored in the stack of memory. Examples of some built-in value types are Numeric types (sbyte, byte, short, int, long, float, double, decimal), char, bool, IntPtr, date, Struct and Enum is the value type.

If I need to create a new value type, then I can use structs to create a new value type. I can also use enum keyword to create a value type of enum type.


Reference types


Reference types store the address of their data i.e. pointer on the stack and actual data is stored in heap area of the memory. The heap memory is managed by the garbage collector.

As I said, the reference type does not store its data directly, so assigning a reference type value to another reference type variable creates a copy of the reference address (pointer) and assign it to the 2nd reference variable. Thus, now both the reference variables have the same address or pointer for which an actual data is stored in heap. If I make any change in one variable, then that value will also be reflected in another variable. 

In some cases, it is not valid like when reallocating memory, it may update only one variable for which new memory allocation has been done.

Suppose you are passing an object of customer class, let's say “objCustomer” inside a method “Modify(…)” and then re-allocate the memory inside the “Modify(…)” method & provide its properties value. In that case, customer object “objCustomer” inside the “Modify(…)” will have different value and those change will not be available to the variable “objCustomer” accessed outside of “Modify(…)”.

You can also take the example of String class. ‘string’ is the best example for this scenario because in the case of a string, each time new memory is allocated. 

I will explain about all those scenarios in depth in “Usage of ‘ref’ & ‘out’ keyword in C#” & “Understanding the behavior of ‘string’ in C#” section of this article.

التعليقات



إذا أعجبك محتوى مدونتنا نتمنى البقاء على تواصل دائم ، فقط قم بإدخال بريدك الإلكتروني للإشتراك في بريد المدونة السريع ليصلك جديد المدونة أولاً بأول ، كما يمكنك إرسال رساله بالضغط على الزر المجاور ...

إتصل بنا

المشاركات الشائعة

معلومات كل ساعة

مدونة معلومات كل ساعة هدفها توفير كافة المعلوماتت التي يمكنها مساعدتك في حياتك اليومية.

جميع الحقوق محفوظة

معلومات كل ساعه

2016