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

Java and C# Equivalents


Equivalents were produced with Java to C# Converter and C# to Java Converter.      


C# and Java have identical syntax for abstract methods:

Java C#
public abstract class AbstractClass
{
    public abstract void AbstractMethod();
}
public abstract class AbstractClass
{
    public abstract void AbstractMethod();
}
Java C#
public
no access modifier (package access)
private
no exact equivalent
protected
public
internal
private
protected
protected internal

The closest equivalent to Java anonymous inner classes in C# is to use a private class which implements the corresponding interface (but if the interface is a functional interface, then the closest equivalent is to replace the functional interface with a delegate and the anonymous inner class with a lambda).

Java C#
public class TestClass
{
    private void TestMethod()
    {
        MyInterface localVar = new MyInterface()
        {
            public void method1()
            {
                someCode();
            }
            public void method2(int i, boolean b)
            {
                someCode();
            }
        };
    }
}
public class TestClass
{
    private void TestMethod()
    {
        MyInterface localVar = new MyInterfaceAnonymousInnerClass(this);
    }

    private class MyInterfaceAnonymousInnerClass : MyInterface
    {
        private readonly TestClass outerInstance;

        public MyInterfaceAnonymousInnerClass(TestClass outerInstance)
        {
            this.outerInstance = outerInstance;
        }

        public virtual void method1()
        {
            someCode();
        }
        public virtual void method2(int i, bool b)
        {
            someCode();
        }
    }
}

Unsized Array

Java C#
int[] myArray = null; int[] myArray = null;   //no change

Sized Array

Java C#
int[] myArray = new int[2]; int[] myArray = new int[2];   //no change

Access Array Element

Java C#
x = myArray[0]; x = myArray[0];   //no change

Jagged Array

Java C#
int[][] myArray = new int[2][]; int[][] myArray = new int[2][];   //no change

Rectangular Array

Java C#
int[][] myArray = new int[2][3]; int[][] myArray = RectangularArrays.ReturnRectangularIntArray(2, 3);

//----------------------------------------------------------------------------------------
// Copyright © 2007 - 2017 Tangible Software Solutions Inc.
// This class can be used by anyone provided that the copyright notice remains intact.
//
// This class includes methods to convert Java rectangular arrays (jagged arrays
// with inner arrays of the same length).
//----------------------------------------------------------------------------------------
internal static class RectangularArrays
{
    internal static int[][] ReturnRectangularIntArray(int size1, int size2)
    {
        int[][] newArray = new int[size1][];
        for (int array1 = 0; array1 < size1; array1++)
        {
            newArray[array1] = new int[size2];
        }

        return newArray;
    }
}
C# Java
//List:
List<int> myList = new List<int>() {1, 2, 3};

//Dictionary:
Dictionary<string, int> myD = new Dictionary<string, int>() {
    {string1, 80},
    {string2, 85}
};
import java.util.*;

//ArrayList: (Java 9 List.of would also work here)
ArrayList<Integer> myList = new ArrayList<Integer>(Arrays.asList(1, 2, 3));

//HashMap: (Map.ofEntries requires Java 9)
HashMap<String, Integer> myD = new HashMap<String, Integer>(Map.ofEntries(Map.entry(string1, 80), Map.entry(string2, 85)));

ArrayLists/Lists

Java's java.util.ArrayList collection and the .NET System.Collections.Generic.List collection are very close equivalents.

Java C#
void ArrayLists()
{
    java.util.ArrayList<Integer> myList = new java.util.ArrayList<Integer>();
    myList.add(1);
    myList.add(1, 2);
    int i = 1;
    myList.set(0, i);
    i = myList.get(0);
}
using System.Collections.Generic;

void ArrayLists()
{
    List<int?> myList = new List<int?>();
    myList.Add(1);
    myList.Insert(1, 2);
    int i = 1;
    myList[0] = i;
    i = myList[0].Value;
}

HashMaps/Dictionaries

Java's java.util.HashMap collection and the .NET System.Collections.Generic.Dictionary collection are very close equivalents.

Java's java.util.TreeMap collection and the .NET System.Collections.Generic.SortedDictionary collection are also very close equivalents.

Java C#
void HashMaps()
{
    java.util.HashMap<String, Integer> map = new java.util.HashMap<String, Integer>();
    String s = "test";
    map.put(s, 1);
    int i = map.get(s);
    i = map.size();
    boolean b = map.isEmpty();
    map.remove(s);
}
using System.Collections.Generic;

void HashMaps()
{
    Dictionary<string, int?> map = new Dictionary<string, int?>();
    string s = "test";
    map[s] = 1;
    int i = map[s].Value;
    i = map.Count;
    bool b = map.Count == 0;
    map.Remove(s);
}

Local Constant

C# Java
const int myConst = 2; final int myConst = 2;

Class Constant

C# Java
public const int myConst = 2; public static final int myConst = 2;

Local Variable

C# Java
int myVar = 2; int myVar = 2;

Inferred Types

There is no inferred typing in Java, so the type is inferred by the converter:

C# Java
var myVar = 2; int myVar = 2;

Static Field

C# Java
public static int S; public static int S;

Read-Only Field

C# Java
public readonly int R = 2; public final int R = 2;
C# Java
class Foo
{
    public Foo() : this(0) //call to other constructor
    {
    }

    public Foo(int i)
    {
    }

    ~Foo()
    {
    }
}
class Foo
{
    public Foo()
    {
        this(0); //call to other constructor
    }

    public Foo(int i)
    {
    }

    protected void finalize() throws Throwable
    {
    }
}
Java C#
int
boolean
java.lang.String (no Java language type)
char
float
double
java.lang.Object (no Java language type)
java.math.BigDecimal (no Java language type)
short
long
no unsigned types in Java
byte (signed byte)
no unsigned types in Java
no unsigned types in Java
no unsigned types in Java
int
bool
string
char
float
double
object
decimal
short
long
byte (unsigned byte)
sbyte (signed byte)
ushort (unsigned short)
uint (unsigned int)
ulong (unsigned long)

Simple enums in Java have simple equivalents in C#:

Java C#
public enum Simple
{
    FOO,
    BAR
}
public enum Simple
{
    FOO,
    BAR
}

More complex enums in Java unfortunately have exceedingly complex equivalents in C#:

Java C#
public enum Complex
{
    FOO("Foo"),
    BAR("Bar");

    private final String value;

    Complex(String enumValue)
    {
        this.value = enumValue;
    }

    public void InstanceMethod()
    {
        //...
    }
}
using System.Collections.Generic;

public sealed class Complex
{
    public static readonly Complex FOO = new Complex("FOO", InnerEnum.FOO, "Foo");
    public static readonly Complex BAR = new Complex("BAR", InnerEnum.BAR, "Bar");

    private static readonly IList<Complex> valueList = new List<Complex>();

    static Complex()
    {
        valueList.Add(FOO);
        valueList.Add(BAR);
    }

    public enum InnerEnum
    {
        FOO,
        BAR
    }

    public readonly InnerEnum innerEnumValue;
    private readonly string nameValue;
    private readonly int ordinalValue;
    private static int nextOrdinal = 0;

    private readonly string value;

    internal Complex(string name, InnerEnum innerEnum, string enumValue)
    {
        this.value = enumValue;

        nameValue = name;
        ordinalValue = nextOrdinal++;
        innerEnumValue = innerEnum;
    }

    public void InstanceMethod()
    {
        //...
    }

    public static IList<Complex> values()
    {
        return valueList;
    }

    public int ordinal()
    {
        return ordinalValue;
    }

    public override string ToString()
    {
        return nameValue;
    }

    public static Complex valueOf(string name)
    {
        foreach (Complex enumInstance in Complex.valueList)
        {
            if (enumInstance.nameValue == name)
            {
                return enumInstance;
            }
        }
        throw new System.ArgumentException(name);
    }
}

Java does not have any syntax which is specific to events. C# has the event keyword which allows you to declare an event to which you can easily subscribe or unsubscribe multiple listeners in addition to letting all the listeners know when the event occurs. To do this in Java, you need to replace the event's delegate type with a functional interface and replace the event declaration with a new field declaration using our generic 'Event' helper class. The 'Event' class takes care of two different listener collections and has methods for adding or removing an event subscription. Two different collections are necessary since C# allows subscribing to an event by specifying a method name or delegate instance(named listener) or subscribing by specifying a lambda.

Here's a simple example:

C#:

public class EventSource
{
    public delegate void FooDelegate();
    public event FooDelegate FooEvent;

    private void RaiseFooEvent()
    {
        FooEvent();
    }
}

public class EventClient
{
    public void SubscribeAndUnsubscribe()
    {
        EventSource t = new EventSource();
        //subscribe via method name:
        t.FooEvent += HandleFooEvent;
        //unsubscribe via method name:
        t.FooEvent -= HandleFooEvent;

        //subscribe via lambda:
        t.FooEvent += () =>
        {
            HandleFooEvent();
        };
    }

    private void HandleFooEvent()
    {
    }
}

Java:

public class EventSource
{
    @FunctionalInterface
    public interface FooDelegate
    {
        void invoke();
    }
    public Event<FooDelegate> FooEvent = new Event<FooDelegate>();

    private void RaiseFooEvent()
    {
        //invoke all listeners:
        for (FooDelegate listener : FooEvent.listeners())
        {
            listener.invoke();
        }
    }
}

public class EventClient
{
    public final void SubscribeAndUnsubscribe()
    {
        EventSource t = new EventSource();
        //subscribe via method name:
        t.FooEvent.addListener("HandleFooEvent", () -> HandleFooEvent());
        //unsubscribe via method name:
        t.FooEvent.removeListener("HandleFooEvent");

        //subscribe via lambda:
        t.FooEvent.addListener(() ->
        {
            HandleFooEvent();
        });
    }

    private void HandleFooEvent()
    {
    }
}

//----------------------------------------------------------------------------------------
// 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 convert C# events to Java.
//----------------------------------------------------------------------------------------
public final class Event<T>
{
    private java.util.Map<String, T> namedListeners = new java.util.HashMap<String, T>();
    public void addListener(String methodName, T namedEventHandlerMethod)
    {
        if (!namedListeners.containsKey(methodName))
            namedListeners.put(methodName, namedEventHandlerMethod);
    }
    public void removeListener(String methodName)
    {
        if (namedListeners.containsKey(methodName))
            namedListeners.remove(methodName);
    }

    private java.util.List<T> anonymousListeners = new java.util.ArrayList<T>();
    public void addListener(T unnamedEventHandlerMethod)
    {
        anonymousListeners.add(unnamedEventHandlerMethod);
    }

    public java.util.List<T> listeners()
    {
        java.util.List<T> allListeners = new java.util.ArrayList<T>();
        allListeners.addAll(namedListeners.values());
        allListeners.addAll(anonymousListeners);
        return allListeners;
    }
}

Java doesn't have extension methods, so a C# extension method is just converted to an ordinary Java static method (calls to the method have to be adjusted to static calls using the class name).

C# Java
public static class ContainsExtension
{
    public static void ExtensionMethod(this string myParam)
    {
        //...
    }
}
class TestClass
{
    void TestMethod()
    {
        string s;
        s.ExtensionMethod();
    }
}
public final class ContainsExtension
{
    public static void ExtensionMethod(String myParam)
    {
        //...
    }
}
public class TestClass
{
    private void TestMethod()
    {
        String s;
        ContainsExtension.ExtensionMethod(s);
    }
}
Java C#
for (String s : StringList)
{
    ...
}
foreach (string s in StringList)
{
    ...
}

Java's functional interfaces are closely related to C# delegates.

Java C#
@FunctionalInterface
public interface FooFunctional
{
    void invoke();
}

public class UseFunctionalInterface
{
    void method()
    {
        FooFunctional funcVar = () -> voidMethod();
        funcVar.invoke();
    }
    void voidMethod()
    {
    }
}
public delegate void FooFunctional();

public class UseFunctionalInterface
{
    internal virtual void method()
    {
        FooFunctional funcVar = () => voidMethod();
        funcVar();
    }
    internal virtual void voidMethod()
    {
    }
}

Java generics and C# generics are implemented in totally different ways - Java generics uses the concept of 'type erasure' (compiling to Object and casts), while C# generics is a run-time feature, but you can still often achieve the same result by converting one to the other.

Defining a Generic Class

Java C#
public class GenericClass<T> public class GenericClass<T>

Defining a Generic Class with a Constraint

Java C#
public class GenericClass<T extends SomeBase> public class GenericClass<T> where T: SomeBase

Defining a Generic Method

Java C#
public <T> void Method(T param) public void Method<T>(T param)

Defining a Generic Method with a Constraint

Java C#
public <T extends SomeBase> void Method(T param) public void Method<T>(T param) where T: SomeBase
Java C#
import Foo.*;
import static Foo.Bar.*;

*no equivalent*
*no equivalent*
using Foo;
using static Foo.Bar;

//namespace alias:
using foo = SomeNamespace;
//type alias:
using bar = SomeNamespace.SomeType;

Java does not have indexers, so you must use get/set methods instead:

C# Java
public int this[int index]
{
    get
    {
        return field[index];
    }
    set
    {
        field[index] = value;
    }
}
public final int getItem(int index)
{
    return field[index];
}
public final void setItem(int index, int value)
{
    field[index] = value;
}

Basic Inheritance

C# Java
class Foo : SomeBase
{
}
class Foo extends SomeBase
{
}

Inheritance Keywords

C# Java
abstract    (class)
abstract    (method)
override (method)
sealed    (class)
sealed    (method)
new (shadowing)
abstract    (class)
abstract    (method)
@Override (method annotation)
final    (class)
final    (method)
no Java equivalent

Defining Interfaces

Java C#
public interface IFoo
{
    void Method();
}
public interface IFoo
{
    void Method();
}

Implementing Interfaces

Java C#
public class Foo implements IFoo
{
    public void Method()
    {
    }
}
//implicit implementation:
public class Foo : IFoo
{
    public void Method()
    {
    }
}

//explicit implementation:
public class Foo : IFoo
{
    void IFoo.Method()
    {
    }
}

Expression Lambda

Java C#
myVar = (String text) -> text.Length; myVar = (string text) => text.Length;

Block Lambda

Java C#
myVar = (String text) ->
{
    return text.Length;
}
myVar = (string text) =>
{
    return text.Length;
}

Most programming languages allow 'overloading' operators to implement specialized behavior for the operator when used on instance of a type. Java doesn't allow this, but the same behavior is achieved through static methods:

C# Java
public class SomeType
{
    private int IntValue;

    public static int operator +(SomeType X, SomeType Y)
    {
        return X.IntValue + Y.IntValue;
    }

    public void OperatorTest()
    {
        SomeType o1 = new SomeType();
        SomeType o2 = new SomeType();
        int i = o1 + o2;
    }
}
public class SomeType
{
    private int IntValue;

    public static int OpAddition(SomeType X, SomeType Y)
    {
        return X.IntValue + Y.IntValue;
    }

    public final void OperatorTest()
    {
        SomeType o1 = new SomeType();
        SomeType o2 = new SomeType();
        int i = SomeType.OpAddition(o1, o2);
    }
}

Java does not allow optional parameters.  Overloaded methods are the only alternative in Java to optional parameters (these are inserted into the converted code by C# to Java Converter).  A C# method with n optional parameters is converted to n + 1 overloaded methods.  The overloaded methods call the overloaded method with the maximum number of parameters (which contains your original method code), passing the default values originally specified for the original optional parameters.

Here's an example of the simplest possible case:

C# Java
public void TestOptional(int x = 0)
{
    ...
}
public void TestOptional()
{
    TestOptional(0);
}
public void TestOptional(int x)
{
    ...
}
Java C#
package FooPackage; //only one per file

public class FooClass
{
}
namespace FooPackage //can have many per file
{
    public class FooClass
    {
    }
}
Java C#
private void Method(Object... myParam)
{
}
void Method(params object[] myParam)
{
}

Java does not have properties, so you must use get/set methods instead:

C# Java
public int IntProperty
{
    get
    {
        return intField;
    }
    set
    {
        intField = value;
    }
}
public int getIntProperty()
{
    return intField;
}
public void setIntProperty(int value)
{
    intField = value;
}

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;
    }
}

Java static initializer blocks and C# static constructors serve the same purpose.

Java C#
class Foo
{
    public static int field;

    static
    {
        field = 1;
    }
}
class Foo
{
    public static int field;

    static Foo()
    {
        field = 1;
    }
}
Java C#
synchronized (x)
{
    ...
}
lock (x)
{
    ...
}
Java C#
boolean b = f instanceof Foo;
Class t = w.class;
bool b = f is Foo;
Type t = typeof(w);

The C# 'using' statement (not the C# 'using' directive) is a shortcut for a try/finally block which disposes an object of type System.IDisposable. Java 7 introduces the 'try with resources' statement, which operates on objects of type java.io.Closeable:

C#:

using (Foo f = new Foo())
{
}

Java 7 or higher:

try (Foo f = new Foo())
{
}

pre-Java 7:

Foo f = new Foo();
try
{
}
finally
{
    f.close();
}

Java doesn't have verbatim strings, so the closest you can get is a string concatenation which spans multiple lines.

C# Java
string s = @"multiline
    verbatim
    string";
String s = "multiline" + "\r\n" +
    " verbatim" + "\r\n" +
    " string";

Copyright © 1997 – 2017 Tangible Software Solutions Inc.