Click here to Skip to main content
15,906,574 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello
i have an array in form1 and i send it as ref to form2 constructor
in form2 i want to make the array as "global" to use it in various methods

form1 call
C#
Form2 form = new ImageView(ref array1);
            form.ShowDialog();


form2 constructor
C#
public Form2(ref string[] arr)
        {
            InitializeComponent();
            
        }




or give me another way can i use.
Posted

 
Share this answer
 
Comments
M. Daban 26-Jul-14 9:24am    
Is there a solution other than this?
Thomas Daniels 26-Jul-14 11:08am    
Yes, if you don't want to create a Singleton as Sergey said in his answer, you can use a class that every method can access, see my answer there.
If you want to make your array used across form2 only, pass it from form1 to 2 and then store it in a class level variable.
 
Share this answer
 
Comments
M. Daban 26-Jul-14 9:21am    
i pass it to form2 constructor , but i want to store it in class level as reference
Abhinav S 26-Jul-14 9:48am    
Just declare it as a class level variable as use it across the form.
You don't need to use ref anywhere.
Note that array is a reference type. There is no a need to pass it by reference. Such double reference would only be useful if you want to replace the array object by some of such functions. It can really be needed if you want to change the array length, as an array is immutable in this respect (but then it would be strongly recommended to use some collection instead of array).

Overall, passing an array by reference is practically quite useless. If the functions just modify some elements, you don't need "ref", and if you want to change the length, array should not be used. Finally, if you want to replace the whole array by some functions by whatever reason, it could not touch the "global" (more exactly, outer-scope array). Only the calling method would receive the replaced object.

Even more importantly: the idea to mimic "global" objects (real global objects are not available in .NET, for some very good reasons) is really, really bad. If you properly analyze your code design, you may come to conclusion that this is never needed but can be disastrous. Just don't do it. If you could explain the your ultimate goals, perhaps I would be able to suggest what to do instead.

—SA
 
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