Generic Variable Parameters

Hi there,

I’m merging two instances of a custom class, and currently I go through every variable like so (There’s many variables.):

if (c.characterPortraitWidth != null) { characterPortraitWidth = c.characterPortraitWidth; }
if (c.characterPortraitHeight != null) { characterPortraitHeight = c.characterPortraitHeight; }

I was wondering if there’s a way to make a function along the lines of:

void MergeVariable(var newValue, var originalValue){
    if(newValue != null) { originalValue = newValue; }

Any help appreciated!

In C# you can make use of some operators:

// null-coalescing operator:
// as  Huacanacha said in comment, this will only work if newVar is nullable.
// returns oldvar, if oldvar != null, else returns the value after the ??, 15 in this case:
float newVar = oldvar ?? 15;

// conditional operator
// if oldvar is null, newVar gets the value 1, else newvar gets the value of oldvar.
float newVar = oldvar == null ? 1 : oldvar;

Use a ref parameter. This passes the variable by reference so you can change it’s assignment. You’ll have to use nullable types such as float? if you want to check for a value type being null.

void AssignIfNotNull<T>(T? newValue, ref T receiver) where T : struct {
receiver = newValue ?? receiver;

Then call it like this:

float original = 3;
float? newValue = 7;
AssignIfNotNull(newValue, ref original); // original is set to 7

original = 3;
newValue = null;
AssignIfNotNull(newValue, ref original); // original stays 3

If you have classes rather than value types it’s even easier as you could use the null coalescing operator, or choose to use a helper function:

// Direct way
receiver = newObj ?? receiver;

// OR you can use a function
void AssignIfNotNull<T>(T newValue, ref T receiver) where T : class {
    receiver = newValue ?? receiver;

This will cause receiver and newObj to point to the same object if the assignment is successful.