A Guide to Converting Java to C#

C# and Java are fairly similar languages. They are similar enough that projects, such as our Encog project, can be converted to C#. Yet they are different enough that this is not always a 100% straight forward process. Additionally, there are several considerations to take into account so that your Java program does not look like a "Java Program converted to C#". C# programs support unique indexing options, properties and many other features that are not available to Java programs. For a true translation, it is important to use these as well.

For Each

A Java "for each" looks like this.

for (final HistogramElement element : this.sorted)
{
}

A C#"for each" looks like this.

foreach (HistogramElement element in this.sorted)
{
}

2D Arrays

In Java an array can be declared by attaching the [] to either the variable name or the type.

private double input[];
private double ideal[];

In C# the [] must be attached to the type.

private double[] input;
private double[] ideal;

Case Insensitive String Compare

In Java, you can compare two strings, ignoring case, as follows:

if( str.equalsIgnoreCase("Hello World") )
{
}

In C# this becomes:

if( string.Compare(str, "Hello World",true) )
{
}

Method Headers

In Java, you must declare any checked exceptions that are thrown with the "throws" keyword. Also parameters should be declared as final.

public void process(final int i) throws IOException

In C#, there are no checked exceptions, and parameters are not declared final.

public void process(int i) 

StringTokenizer

One of the most commonly used utility classes in Java is often the StringTokenizer. You can see the StringTokenizer class in use here.

StringTokenizer tok = new StringTokenizer(line);

while (tok.hasMoreTokens()) 
{
  String word = tok.nextToken();
  buildFromWord(word);
}

C# has no StringTokenizer. A quick conversion follows.

string[] tok = line.Split();

for(int i=0;i

instanceof

Java

if (layer instanceof FeedforwardLayer) 
{
}

C#

if (layer is FeedforwardLayer) 
{
}

Reflection

this.workloadManager = (WorkloadManager)Assembly.GetExecutingAssembly().CreateInstance(this.options.WorkloadManager);

Comments

I am currently learning C++.

andyflower52's picture

I am currently learning C++. This tutorial is very much essential for me. I am very much thankful to this site.

actually

jeffheaton's picture

This guide would be nearly useless to a C++ programmer. This is for C#, which is a different language than C++.

good guid

james's picture

very good guide, thanks a lot.


Copyright 2005 - 2010 by Heaton Research, Inc.. Heaton Research™ and Encog™ are trademarks of Heaton Research. Click here for copyright and trademark information.