Passing arguments by reference with "ref" keyword

You are browsing legacy Javonet 1.5 (Java<>.NET bridge for Windows) documentation. Use the left side menu or click here to switch to latest Javonet 2.0 documentation. Javonet 2.0 allows you to use any module from JVM, CLR, Netcore, Python, Ruby, Perl, NodeJS on Windows, Linux and MacOs from any application created in Java, Clojure, Groovy, Kotlin, C#, F#, J#, VB.NET, Python, Perl, Ruby, JavaScript, TypeScript, C++ and GoLang

Microsoft .NET allows you to create methods that expect arguments to be passed by reference.
Passing by reference is introduced by explicitly setting ref or out keywords before argument type within the method definition. For example, void MethodWithRefArg(ref int arg).

Note: Passing arguments by reference should not be confused with passing reference-type arguments described in the previous section. If you need just to pass another .NET object in method arguments, please see the previous section.

Javonet allows you to pass by reference both .NET objects (NObject) or primitive types (String, Integer, Float, Boolean etc..). You can also pass arrays of these types like NObject[] or String[].

While passing variables by reference, the value of that variable might be modified within the method body. Read more about .NET ref and out keywords here:

Javonet allows you to invoke methods expecting ref arguments by providing dedicated type: NRef. To pass the variable by reference, you must wrap the variable with the NRef class. For NObject and NObject[], you can wrap them with NRef directly. However because Java does not support passing by reference primitive types, both variables (like String, Integer, Boolean etc.) or arrays of them should be wrapped with the "AtomicReference<?>" class, and then wrapped with NRef object.

Example .NET class with expecting ref argument method:

public class TestClass {
    public TestClass() {
    }

    public static int MyStaticField;

    public int MyInstanceField;

    public static String SayHello(String name) {
        return "Hello " + name;
    }

    public static int MethodExpectingPrimitiveInt(int arg) {
        return arg * 2;
    }

    public static int MethodExpectingClassInteger(Integer arg) {
        return arg * 2;
    }

    public int MultiplyByTwo(Integer arg) {
        return arg * 2;
    }

    public <T> T MyGenericMethod(T arg1)
    {
        return arg1;
    }
}

Example of a ref argument method from Java using Javonet

I code in:

Select language you code in:

See Live Example!