Search code examples
c#returnref

which is better in this case, return or 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?


Solution

  • 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.