Search code examples
c#pointersparametersrefout

C# difference between ref and complex object as parameter


I'm curious what happens if I do not use the ref declaration for a parameter, instead pass the object it self and manipulate it within the function.

E.g:

public void DoStuff(DataPackage context) 
{
    context.IsAValue = false;
}

var context = new DataPackage();
DoStuff(context);

Assert.False(context.IsAValue)

And here the other variation:

public void DoStuff(ref DataPackage context) 
{
    context.IsAValue = false;
}

var context = new DataPackage();
DoStuff(ref context);

Assert.False(context.IsAValue)

I think sometimes in complex scenarios, the pass without the ref does not work like assumed here. Is that true? I´m facing an issue which lets me think that way.

Hope for help.


Solution

  • In your second example var context = new DataPackage(); will be ignored and this is intended behavior.

    In both examples context.IsAValue is false unless its initialized as true

    Your second example is an incorrect usage of ref

    example as per the Reference

    Don't confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference.

    void Method(ref int refArgument)
    {
        refArgument = refArgument + 44;
    }
    
    int number = 1;
    Method(ref number);
    Console.WriteLine(number);
    // Output: 45
    

    Also look at: passing an argument by reference an example

    The ref keyword indicates that a value is passed by reference. It is used in four different contexts:

    1. In a method signature and in a method call, to pass an argument to a method by reference. For more information, see Passing an argument by reference.

    2. In a method signature, to return a value to the caller by reference. For more information, see Reference return values.

    3. In a member body, to indicate that a reference return value is stored locally as a reference that the caller intends to modify. Or to indicate that a local variable accesses another value by reference. For more information, see Ref locals.

    4. In a struct declaration, to declare a ref struct or a readonly ref struct. For more information, see the ref struct section of the Structure types article.