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:

using System;

namespace TestNamespace
{
	public class TestClass
	{
		public TestClass() { }
		~TestClass()
		{
			Console.WriteLine("Displaying object from .NET destructor message");
		}
		public static int MyStaticField { get; set; }
		public int MyInstanceField { get; set; }

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

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

		public T MyGenericMethod<T>(T arg1)
		{
			return arg1;
		}
		public K MyGenericMethodWithTwoTypes<T, K>(T arg1)
		{
			return default(K);
		}

		public void MethodWithRefArg(ref int arg)
		{
			arg = arg + 44;
		}

		public string PassTypeArg(Type myType)
		{
			return myType.ToString();
		}

		public string MethodWithEnumArg(SampleEnum value)
		{
			return value.ToString();
		}
	}
}

Example of a ref argument method from Java using Javonet

I code in:

Select language you code in:

See Live Example!