Click here to Skip to main content
15,902,445 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please see the code snippet...

C#
class a
   {
       int[] cr=new int[10];
       public void add(int[] br)
       {
           cr[0] = 111;
           br=cr;
       }
   }
   class Program
   {

       static void Main(string[] args)
       {
              int[] ar = new int[10];
              ar[0] = 55;
           a obj = new a();
           obj.add(ar);
           Console.WriteLine(ar[0]);

       }


Why the reference of the 'ar[]' is not changing to 'cr[]' ?
Posted
Comments
Sergey Alexandrovich Kryukov 17-Apr-12 11:39am    
In what like do you think you change the reference? -- I don't see such thing. :-)
--SA

Because you are passing ar by value when you would want to pass it by reference.
 
Share this answer
 
Comments
Espen Harlinn 18-Apr-12 18:03pm    
5'ed!
[no name] 18-Apr-12 18:29pm    
Thanks
C#
class a
   {
       int[] cr=new int[10];      //think cr address is [3000]
       public void add(int[] br)   //getting 2000=>br
       {
           cr[0] = 111;           
           br=cr;                  //br=cr means br=3000,it doesn't mean ar=3000
       }                           //because it is value, not reference
   }
   class Program
   {

       static void Main(string[] args)
       {
              int[] ar = new int[10];   //think ar address is [2000] 
              ar[0] = 55;
           a obj = new a();
           obj.add(ar);      //passing 2000
           Console.WriteLine(ar[0]);

       }
 
Share this answer
 
v2
try this:

C#
class a
   {
       int[] cr=new int[10];
       public int[] add(/*int[] br*/)
       {
           cr[0] = 111;
           //br=cr;
           return cr;
       }
   }
   class Program
   {
 
       static void Main(string[] args)
       {
              int[] ar = new int[10];
              ar[0] = 55;
           a obj = new a();
           //obj.add(ar);
           arr = obj.add();
           Console.WriteLine(ar[0]);
 
       }


I did it quick and dirty, but I think it is because br is not coming out the function. if you want to pass an argument and change it, you need to use the ref or out keyword (see MSDN)

hope this helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900