-1

I have a question: is it possible to edit the entry of the function without returning any value and those entries will be edited?

Idea:

void AddGreeting(string value)
{
    value = "Hi " +value;
}

and calling this function like this:

string test = "John"; 
AddGreeting(test);
//and here the test will be "Hi John"

is that possible? and how to do it if it is?

Samy Sammour
  • 2,298
  • 2
  • 31
  • 66

1 Answers1

2

You could easily use the ref parameter as so:

void AddGreeting(ref string value){}

and this would do what you want:

void AddGreeting(ref string value)
{
    value = "Hi " +value;
}

string test = "John"; 
AddGreeting(ref test);

Alternatively, you could return a string, which i would consider neater and cleaner to look at

  • Note that as strings are immutable you aren't *actually* modifying value, rather assigning it to a *new* string. – BradleyDotNET Nov 29 '16 at 18:54
  • I would agree that returning a value is easier to read. I will use ref if I need to modify multiple variables, but that is rare as well as in those cases I am usually modifying a class property or will pass in an object that has multiple properties. – Joe C Nov 29 '16 at 18:55
  • thank you, I guess that will answer my questions. I am trying to write a code to read the string parameters of a generic object and delete sql injection and return the same object. – Samy Sammour Nov 29 '16 at 18:58
  • have youi thought of using reflection instead? –  Nov 29 '16 at 18:59