How to change and return value from within a function

263 Views Asked by At

I am given a code block (C#) and want to change and return a new value (e.g., 9999) in the variable gid. However, the new value is not being returned. The original value used in the function call has not changed. How do I force a change in the value of the variable?

This is the code block:

public uint? GeneratePrimaryGid(DirectoryEntry de, uint? gid, int option)
{
    gid = 9999;
    return gid;
}

Unfortunately, passing it by reference, using the ref keyword, did not work. As a comparison, here is the code segment for changing the Unix shell:

    public string GenerateShell(DirectoryEntry de, string shell, int option)
    {
        return shell;
    }

When I add this line before the return: shell = "/bin/test";

I can see that the shell is set to /bin/test, even tho the value that was passed to the function was '/bin/bash'. In fact, when the parameter is of type 'string', the changes are reflected. Just not when the type is 'unit?'.

1

There are 1 best solutions below

0
Rufus L On

For this answer I'm simplifying the method signature to only contain the argument that's being changed:

public uint? GeneratePrimaryGid(uint? gid)

You stated:

I am given a code block and want to change and return a new value (e.g., 9999) in the variable gid

Returning a value and changing a value are two different things. Your method is successfully returning the value you want here:

return gid;

The part that is possibly confusing you is that, because uint? is a value type, you're only getting a copy of the value in the argument, so when you modify it, there is no change to the value of the variable on the caller's side. In order to change the value for the caller, you need to pass it by reference, using the ref keyword:

public uint? GeneratePrimaryGid(ref uint? gid)
{
    gid = 9999;
    return gid;
}

Now you are both returning the value and changing the value of the variable on the caller's side.