Java simple example

CSharp Class Use Examples

This is a basic example where a developer call, from a Java application, the simple class defined in a file named CSharpClass.cs.

Let’s consider the following C# code:

using System;

namespace MASES.CLRTests
    public class CSharpClass
        /// <summary>The method <c>HelloWorld</c> return the "Hello World!!" string</summary>
        public String HelloWorld()
            return "Hello World from C#!!";

        /// <summary>The method <c>Add</c> return the sum of two double</summary>
        public double Add(double a, double b)
            return a + b;

        /// <summary>The method <c>Add</c> return the sin of a double</summary>
        public double Sin(double a)
            return Math.Sin(a);

Compiling it with the preferred development tools an assembly will be generated.

Create a Java class named with the following content:

import org.mases.jcobridge.*;

public class CSharpClassUseExample {
    public static void main(String[] args) {
        try {
            try {
                try {
                    } catch (JCException e) {
                } catch (IOException e) {
                //declare and create JCOBridge instance
                JCOBridge bridge;
                bridge = JCOBridge.CreateNew();
                // adds the path where extarnal assemblies where found
                // add REFERENCES to the .dll file
                // GENERATE Object
                JCObject cso = (JCObject) bridge.NewObject("MASES.CLRTests.CSharpClass");
                double a = 2;
                double b = 3;
                double c = Math.PI/2;
                //Invoke the C# class methods
                String hello = (String) cso.Invoke("HelloWorld");
                double result = (double) cso.Invoke("Add",a, b);
                double sin = (double) cso.Invoke("Sin", c);
                System.out.println(String.format("%s %.0f + %.0f = %.0f and sin(%.8f) = %.8f", hello, a, b, result, c, sin));

            } catch (JCException jce) {

Save the file in the same folder where is located the assembly generated from C# project and execute the Java class as standard Main-Class.

Executing the code the following output will be generated:

Hello World from C#!! 2 + 3 = 5 and sin(3,14159265) = 1,00000000