Reputation: 19
I wanted to know if it okay to write this kind of method in C# :
public static string foo(string myString){
myString = Regex.Replace(somecode);
return myString;
}
And somewhere else do :
myString => foo(myString)
I am a C user (and C++ but new one) and I think this is very awkward to return an argument passed to the function. With that the program works perfectly but it is bug free ? I tried to look it up online but couldn't find anything relevant.
Thank you for you help !
Upvotes: 0
Views: 479
Reputation: 3037
I wanted to know if it okay
It is valid and it will work correctly.
At the same time, re-using the parameter is considered a bad practice. Introducing an extra variable costs absolutely nothing and aids in readability:
public static string foo(string myString)
{
string result = Regex.Replace(somecode, ...);
return result;
}
And it is also ok to write foo
in the same lambda style you are using it in:
public static string foo(string myString) => Regex.Replace(somecode, myString, ...);
Upvotes: 2
Reputation: 270770
Reassigning a normal parameter like you did here doesn't do anything to the argument passed in, because the reference of the string
is passed as value into the method, so it's fine to do this.
This means that you can just write:
public static string foo(string myString){
return Regex.Replace(somecode);
}
to achieve the exact same thing.
I would say that modifying a parameter is ok, you just have to beware that it actually does not change the argument passed in.
Upvotes: 0
Reputation: 302
Yes it is okay, as you are manipulating your parameter and then you return. Functions are mainly written for this, to do something based on the input (the parameters) or to manipulate the parameters in someway (just as you did)
Upvotes: -1
Reputation: 1149
While you can, you don't necessarily need to. In this case, you don't need to change the value of the argument at all, you can simply:
return Regex.Replace(somecode);
This is okay to do, because you're passing the value of myString
into your argument, and not a reference to the string itself, though it is possible to do this by using the ref
keyword in your parameter declarations.
Upvotes: 1