HellOoo :

my questoin is like this , if I have a function

void hello(string hh){

hh=textbox1.text
}

if I want to take the value of hh from the function 'hello' , to use it in another function , it impossible to make this

void main()
{

hello(hh);
string x=hello(hh); <-wrong
}

so how can I take the value of hh from the function

Thanks

Recommended Answers

All 4 Replies

You can set the variable for passing it into the first method, then use the ref keyword in the parameter field of the method to reference the parameter as the original variable, rather than creating a new copy. Here's an example:

string hh = "Bob";
Hello(hh);
string x = hh;
Console.WriteLine(x);


// ...

private void Hello(ref string hh)
{
	hh = textBox1.Text;
}

The output will be whatever textBox1.Text's text was.

http://msdn.microsoft.com/en-us/library/14akc2c7%28VS.71%29.aspx

hello is returning a void result i would just change that to a string return.

string hh = "";
hh = hello();

string hello()
{
    return textBox1.text;
}

You can set the variable for passing it into the first method, then use the ref keyword in the parameter field of the method to reference the parameter as the original variable, rather than creating a new copy. Here's an example:

string hh = "Bob";
Hello(hh);
string x = hh;
Console.WriteLine(x);


// ...

private void Hello(ref string hh)
{
	hh = textBox1.Text;
}

The output will be whatever textBox1.Text's text was.

http://msdn.microsoft.com/en-us/library/14akc2c7%28VS.71%29.aspx

One thing to be aware of is that passing an object reference can have side effects (in this case, you are using the side effects to get what you want). What this means is that objects/values outside the function can be changed and you might not realize it. Divin757 has what I'd consider a better solution, as there are no side effects from the method.

commented: its not too bad with value types but interesting things can happen with reference types +2

Memory allocation in C# generates some security related problems such as unauthorised access to the data being passed by reference. This is because garbage collector performs the task of deallocating the memory assigned on heap for such variable periodically. In the meantime, some unauthorised access can occur by third party invaders. Data stored on the heap : content of reference-type objects or anything structured inside a reference-type object. An explicit call to Object.Dispose() method by user can be done to avoid this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.