tags:

views:

76

answers:

2

TryParse family of methods uses out parameters; I could give Swap as an example of ref parameters being useful, but are there good examples in the .NET Base Class Library?

+7  A: 

There are quite a few just in mscorlib. Run this to find them, and give it types in different assemblies to show others.

using System;
using System.Linq;

class Test
{    
    static void Main()
    {
        ShowRefsInAssemblyContaining(typeof(string));
    }

    static void ShowRefsInAssemblyContaining(Type exampleType)
    {
        var query = from type in exampleType.Assembly.GetTypes()
                    where type.IsPublic
                    from method in type.GetMethods()
                    where method.GetParameters()
                                .Any(p => p.ParameterType.IsByRef &&
                                         !p.IsOut)
                    select method;

        foreach (var method in query)
        {
            Console.WriteLine(method.DeclaringType + ": " + method);
        }
    }
}

Simplest example: Interlocked.CompareExchange.

(Don't you love LINQ, btw?)

Jon Skeet
LINQ == COOLDidn't know this was possible!!
bbqchickenrobot
Note that it shows both `ref` and `out` parameter methods since CLR doesn't distinguish them, only C# compiler does.
Alexey Romanov
Ooh, good point. Editing...
Jon Skeet
A: 

I believe you meant in the base class libraries...

If so, there are various locations that take ref parameters. One example is Interlocked.Exchange in System.Threading.

Reed Copsey