memory management - reference and value types c# -



learning c# memory management , faced weird me thing.
dynamically allocate memory student object , change in method — being changed.
dynamically allocate memory int object , change in method — isn't being changed. why??

class student {     public int id;     public string name; }  class program {     static void main(string[] args)     {         student s1 = new student();                     s1.id = 5;         s1.name = "myname";          changestud(s1);          console.writeline(s1.id);         console.writeline(s1.name);          int x = new int();         x = 2;         changeint(x);          console.writeline(x);      }      static void changestud(student s)     {         s.id = 500;         s.name = "changedname";     }      static void changeint(int x)     {         x = 500;     } } 

the output is:

500
changedname
2

passing class object value similar passing pointer data structure in non-object-oriented language, because passed memory location of object. since address given, memory address refers can modified.

passing scalar variable value such integer passing value. called method doesn't receive memory location of int, copy of value. changes not modify value in original memory location.


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -