Link to home
Start Free TrialLog in
Avatar of lcoolsingh
lcoolsingh

asked on

References in c#

Hi there,

Im new to c#, and am not understanding 1 aspect of references. Take the following example:
   
        public  class CRunMe{

          public static void Main(){

             string s = "Default val";
             
              CRunMe.ChangeMe(s);
           
              Console.Writeln(s);   // Should show the new value, but it doesnt..
           
          }
         
          public static void ChangeMe(string str){
             
             str = "New value assigned";
     
          }
        }

Now according to me, a string type is a reference type, so in the above example, afer returnining from changeme, the string variable 's' should be changed 2 reflect the new value, but it doesnt... why is this.. surely a reference type like the above should be changed? In c++, whenever you pass something as a pointer or a reference parameter, if your intention is to modify the passed in parameter, then this will happen. However if i use the ref keyword, then this change takes place..

Thanks


Avatar of skpatra
skpatra

By default  all primitive datatypes are passed by value and all objects are passed by reference in c#. "string" is identified as a primitive data type. However, all primitive datatypes can be 'boxed' to object types. The corrsponding object type for the datatype string is String. If you pass a String (not a string, mark the difference in case) as an argument it will be passed by reference.
ASKER CERTIFIED SOLUTION
Avatar of armoghan
armoghan
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
string is a very special case which behaves like a value type
Avatar of lcoolsingh

ASKER

I tried using the uppercase System.String, and passed this into the above function, but unfortunately this did not work either
try  the way i suggested
I used your way, and i know that by using ref or out, the intended modification takes place.. but as the string type is kind of a reference type, i thought this would happen naturally...

Thanks all