Click here to Skip to main content
15,867,860 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
how to pass a list element by ref ?

C#
private void Form1_Load(object sender, EventArgs e)
      {
          List<string> mylist = new List<string>();
          mylist.Add("hi how are you?");
          sara(ref mylist[0]);//there is errore
      }
      public void sara(ref string message)
      {
          message = "hi , i'm fine.";
      }
Posted
Updated 28-Nov-14 11:21am
v2
Comments
Tomas Takac 28-Nov-14 17:10pm    
Well, you use the ref keyword. Can you post some code that shows your problem?
4L4K1 28-Nov-14 17:31pm    
Yes of course .
Sergey Alexandrovich Kryukov 28-Nov-14 17:45pm    
Where? Where is the problem?
—SA
Philippe Mori 28-Nov-14 20:16pm    
By the way, the compiler already explain the problem in the error message. Just just ahve to read it. And you can generally find help for specific error code in MSDN sometime with examples.

You cannot do that, because ref expects variable or array element. Your mylist[0] is an indexer, so basically a method call. In your example you are just returning a value from the method, so there is no need for ref parameter. But I'm sure this is just an example and your real situation is more complicated.

These are interesting to read:
stackoverflow: C# property and ref parameter, why no sugar?[^]
stackoverflow: A property or indexer may not be passed as an out or ref parameter[^]
 
Share this answer
 
Comments
4L4K1 28-Nov-14 18:11pm    
i think you right i cannot do that.
You already correctly passed the string by reference. Note that this is a rare case when passing a reference object by reference makes sense, just because the System.String is immutable, so you cannot modify the same object by its reference and have to create a new one.

But therefore the method, its signature, still has not practical sense. Besides, you completely ignore the input string value. It also makes no sense. If you don't need input value, pass by reference using out, not ref parameter. But then you would better write a string function. If I fix the problem with ignored input, the function could look something like
C#
string Sara(string input) {
    return input + ": I'm fine";
}

Different signature; the method could do the same, but readability and usability is better.

—SA
 
Share this answer
 
Comments
4L4K1 28-Nov-14 18:15pm    
thanks _SA but it is just an example.
Sergey Alexandrovich Kryukov 28-Nov-14 19:47pm    
Nevertheless, I think I answered your question if full. Are you going to accept it formally?
—SA

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