suppose i have the following group of static functions
here i sent the variable by reference:
public static void ProcessEmailMessage(ref string HTML)
{
ModifyLinks(ref HTML);
AddFakeImage(ref HTML);
}
public static void ModifyLinks(ref string HTML)
{
//modify HTML links
}
public static void AddFakeImage(ref string HTML)
{
//adds an image to the HTML
}
and here i sent the variable by value
public static string ProcessEmailMessage(string HTML)
{
HTML = ModifyLinks(HTML);
HTML = AddFakeImage(HTML);
return HTML;
}
public static string ModifyLinks(string HTML)
{
//modify HTML links
return HTML;
}
public static string AddFakeImage(string HTML)
{
//adds an image to the HTML
return HTML;
}
which one makes more sense, and is there any performance difference between the 2?
Avoid using out- and ref parameters if possible.
Methods taking ref and out parameters are more diffcult to use, you need to declare a variable to hold the result, and the semantics is a bit more diffcult to understand. The performance difference (if any) would be negligible.
The Code Analysis in Visual Studio will likely emit a warning for their use in this case.
See http://msdn.microsoft.com/en-us/library/ms182131 for a more detailed description.
There is likely to be more of a performance hit when using ref
, as this amounts to an extra level of indirection when assigning to the variable. However, this difference is likely to be negligible.
I would prefer the forms that return a string, as this is more illustrative of what is actually happening, and allows you to chain method calls together if you prefer:
return AddFakeImage(ModifyLinks(HTML));
With the ref
form you force calling code to declare a variable, and they might not otherwise need to. This hampers readability and increases the incidence of meaningless boilerplate code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With