Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which is better in this case, return or ref

Tags:

c#

return

ref

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?

like image 269
user1590636 Avatar asked Apr 23 '13 17:04

user1590636


2 Answers

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.

like image 59
DeCaf Avatar answered Sep 27 '22 21:09

DeCaf


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.

like image 42
cdhowie Avatar answered Sep 27 '22 20:09

cdhowie