• Saves Valuable Time
  • Trusted Accuracy for 12 Years
  • 15-Day Money-Back Guarantee

Java Equivalent to C# 'ref' Parameters

Java does not support C#-style 'ref' parameters. All Java parameters are passed by value. However, you can wrap the parameter type in another type (we call it 'RefObject') which still allows changes internal to the object.

Here's a simple example:

C#:

public void refParamMethod(ref int i)
{
    i = 1;
}

public void callRefParamMethod()
{
    int i = 0;
    refParamMethod(ref i);
}

Java:

public void refParamMethod(tangible.RefObject<Integer> i)
{
    i.argValue = 1;
}

public void callRefParamMethod()
{
    int i = 0;
    tangible.RefObject<Integer> tempRef_i = new tangible.RefObject<Integer>(i);
    refParamMethod(tempRef_i);
    i = tempRef_i.argValue;
}

package tangible;

//----------------------------------------------------------------------------------------
// Copyright © 2007 - 2017 Tangible Software Solutions Inc.
// This class can be used by anyone provided that the copyright notice remains intact.
//
// This class is used to replicate the ability to pass arguments by reference in Java.
//----------------------------------------------------------------------------------------
public final class RefObject<T>
{
    public T argValue;
    public RefObject(T refArg)
    {
        argValue = refArg;
    }
}


Use C# to Java Converter to convert from C# to Java.     

Additional resource: Java and C# Equivalents


Copyright © 1997 – 2017 Tangible Software Solutions Inc.