Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile

Using C# for Cross-platform Development

4.79/5 (13 votes)
8 Dec 2015CPOL10 min read 63.4K  
If you are a C# fan and want to build applications that reuse the code base for multiple frameworks and platforms, read this post, it would help you get started.

Introduction and Background

I wrote a bunch of articles about C# programming, but all of them were Windows or .NET oriented. I want to write an article about C# programming on multiple platforms. C# is a very powerful and strong programming language with a very solid foundation over programming concepts. The language is indeed designed to work on high-level applications and initially it was designed to run for .NET applications only, but as time passed it got introduced to other platforms and applications too.

In this article, I will share a few things that you can do on Windows and Linux. I don’t own a Macintosh so I won’t be able to share that concept but I guarantee the procedure to program a Mac application in C# is also similar to this one! Cross-platform itself means to be able to do everything that you can do one platform, on another one too. C# is able to do the same, on every platform. The concept only requires to modify your compilers to be able to accept new environments, same thing applies to C++ and Java and other similar high-level programming languages. C# also works in a similar manner. The concept of C# compilation is that the code doesn’t compile down to machine code. Instead C# code is compiled down to a bytecode, which is later assembled and translated to machine code by the virtual machine; .NET’s virtual machine! That is what makes C# programming language very powerful and at the same time flexible and portable programming language.

If you are a “diagram” lover, please view the following image:

IC15013
Image from MSDN article: Introduction to the C# Language and the .NET Framework

The assemblies are sent to virtual machine, which then translates the code using their metadata and other stuff all the way down to the metal. That is exactly, why it is possible to execute the same C# code on every machine, every platform and every architecture (x86 and x64). Although the instructions are different, but bytecode helps C# to be executed on any machine! In this article, I am going to use the same concept (and a tool) to help you write native applications on other platforms, too.

References

If you want to learn more about C# or cross-platform, you may read the following contents:

  1. Cross-platform programming: An open-source overview
  2. Introduction to the C# Language and the .NET Framework

Cross-platform Tools for C#: Mono Project

If you started programming on Windows, you might have used Visual Studio as your first IDE and specifically, chances are that you started programming using C# programming language. C# is widely used, that it managed to get attention of developers from other platforms and systems too. Mono Project is one of such products which came up not in the near future, but had been known since a while. Mono Project was started to provide C# developers a cross-platform experience. Mono Project can be installed on the following platforms:

  1. Windows
  2. Linux
    This counts any of the distro of Linux kernel, Ubuntu, Red Hat and so on.
  3. OS X

Mono Project can then be used to compile the C# projects as a native application on that platform. In my opinion, that is pretty much self-explanatory, each platform has the resources and architecture information and the related binaries used to target the platform, Mono Project uses those resources and compiles the project down to bare metal components.

In this post, I am going to use Mono IDE, not Visual Studio, because Mono is a cross-platform C# development environment, whereas Visual Studio is a Windows-only tool. But C# can be used on other platforms, all thank you to Mono Project! Using Mono Project, you can build:

  1. Console applications in C#
  2. Graphical applications using C#
  3. ASP.NET web applications

Mono Project also allows you to use VB.NET, but I won’t be talking about that, instead I am going to cover C# only.

Getting Started…

First of all, you may want to install the Mono on your environment. If you are using Windows, then (in my opinion), you should consider using Visual Studio. You can get Visual Studio Community for free if you are a student, learner, open-source developer or a small team. That’s the beauty of Visual Studio. But, if you are going to develop applications using C# where Visual Studio is not supported, you should consider downloading and installing Mono Project, which includes everything starting from the Mono documentation, Mono IDE and the compilers for the languages.

I did say that you should try Visual Studio on Windows but if you want to learn other environment on Windows, you can for sure install Mono on your Windows environment too. It would give you a much better experience to program C# applications on non-Windows environment and all by just using terminal or command-line commands to compile and use the application. I have learnt a lot of things by using the terminal in Linux environment, so I would also recommend you guys to give it a try!

Installing Mono

Installing the Mono is different on different environments, on Windows and Mac it is pretty much same. All you have to do is to download the installer and run it. It installs everything for you. But on the environments, like Linux you have to create repositories and then start installing the packages. That takes a bit of time. I will show you how to do that on all of the environments!

1. Installing on Windows/OS X (Mac)

The procedure to install on Windows and Mac is similar. Just download the package and then go install it, by executing the installer. It would install the Mono project including all of the dependencies, files and executables. You can then use your Mono project to build C# applications on platforms, other than .NET themselves.

2. Installing on Linux (or Linux distros)

Now, things here get complicated. In Linux, you are going to use the terminal and then execute the commands to build the repository systems and then install the packages, for every Linux distro, it is a different process so that may also cause a trouble and that is why I won’t be sharing a single script “to rule it all”, instead I will be providing you with a link that contains all of the scripts that you should execute to get your job done! In the Linux environments, you can execute commands differently to have your job done! Head over to this page to find out which command set would work on your environment. That page would give you the commands that you can execute to set up the environment. Rest assured, now you can execute the following command in your own environment to install the Mono assemblies.

sudo apt-get install mono-complete

This command may also differ based on the environment, some may use yum, some may use rpm or others. Please refer to your own installer commands.

Wait, I cannot find the IDE. Where is it?

Correct, until now, you have only installed the binaries and assemblies required to make Mono workable. You have not yet installed the IDE. Until now you just installed the compilers and binaries. To install the IDE, execute the following command:

sudo apt-get install monodevelop

Now, head over to your IDE that was recently installed and start it! You are going to love it, and well, the folks have seriously put some great efforts in it.

Screenshot (1547)

Ubuntu Studio showing the list of IDEs.

Screenshot (1549)

Hello world project opened in Mono Project.

In the next step, I will share a few examples of using C# to build cross-platform applications. Head over to the next step!

References

I am attaching a few good links in this section too:

  1. Visual Studio Community
  2. Mono Project — Official Website
  3. Install Mono

Building the Applications

In this section, I will show you three sample codes for C#, which you already do know in .NET environment. The samples are not to give a new task in C#, but rather just a simple code, to help you understand how C# can be used to execute commands on different environments, different platforms and so on.

Hello World from Linux

First of all, I want to make my application greet me, from a Linux environment, using the same code that you would use on .NET environment. All of you are already aware of the following code:

C#
using System;
using System.Net.Http;

namespace HelloWorld
{
   class MainClass
   {
        public static void Main (string[] args)
        {
            Console.WriteLine ("Hello, who's there?");
            string name = "";
            name = Console.ReadLine ();
            Console.WriteLine (string.Format("Hello {0} from Linux using C#.", name));
        }
    }
}

Aren’t you? Yes, it’s the same “elementary” C# code to greet someone! This time, running on a non-.NET environment. This would just prompt me for some input and then continue to do what it was intended to do.

Screenshot (1550)

Pretty simple, right? But notice that this code now runs on native Linux environment. There is no underground .NET frameworks supporting it. In real, it is the Mono Runtime that actually does the processing underground. Please read the reference to Mono Runtime in the references below.

C# Programming Using Collections

Collections are a great resource in any application, you can accept a long record of user data in a single object, that is of type: Collection. C# has been providing generic programming objects, for collections. Collections are much better than arrays, because collections are mutable, unlike arrays. In this section, I will show you how to write an application that consumes the collections.

I created a class object, to hold the values of the people. Then I created a list to hold “some” people and then printed their values. It is also a similar code.

C#
using System;
using System.Net.Http;
using System.Collections.Generic;

namespace HelloWorld
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            // Create the list of the people.
            var people = new List<Person> ();
            people.Add (new Person { Name = "Afzaal Ahmad Zeeshan", Age = 20 });
            people.Add (new Person { Name = "Sofiya Zeeshan", Age = 19 });
            people.Add (new Person { Name = "Daniyal Ahmad Rizwan", Age = 15 });
            people.Add (new Person { Name = "Eminem", Age = 43 });

            // Printing the details for people.
            foreach (var person in people) {
                Console.WriteLine (person);
            }
        }
    }

    class Person {
        // Provide the attributes.
        public string Name { get; set; }
        public int Age { get; set; }

        // Override the default ToString
        public override string ToString ()
        {
            return string.Format ("[Person: Name={0}, Age={1}]", Name, Age);
        }
    }
}

How this code actually ran, please see below:

Screenshot (1551)

It just prints everything and then terminates. These were a few things that were basic. Let’s try out if C# still has the same power or not, why not try out Internet access in C#?

Using C# to Access Online Resources

Now in this section, I will be referring an online API of my own to access the data. This may make things a bit tough, if you have never worked with System.Net namespaces in .NET framework. I will be using an object from these namespace and then I will call the functions to actually download the data from an online API and then I will print it.

Linux also provides the similar manner to use the TCP/IP protocol that is why C# code written for Windows would work in a similar manner with Linux and other Mac’s OS X system.

In the following code, I have also used another concept in C#, asynchronous programming. Mono supports async models of C#, and you can avail the services right in the IDE, just like Visual Studio. The code I have used is like the one below:

C#
using System;
using System.Net.Http;
using System.Collections.Generic;

namespace HelloWorld
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            downloadAndPrint ();
        }

        private static void downloadAndPrint() {
            System.Threading.Tasks.Task.Run (async () => {
                using (var client = new HttpClient()) {
                     Console.WriteLine ("Downloading the data...");
                     var message = await client.GetStringAsync
				("http://afzaalahmadzeeshan.gear.host/api/sample");
                     Console.WriteLine();
                     Console.WriteLine(message);
                }
            }).Wait();
            Console.WriteLine ("Exiting the function..");
        }
    }
}

The above code simply downloads the response as string and prints it. This shows that C# not only just works in the console, but it also works perfectly with the protocols on different systems. All of this is managed by the Mono Runtime.

Screenshot (1552)

So, I guess this is enough to demonstrate how C# can be used.

References

A few topics that you should consider reading:

  1. The Mono Runtime
  2. HttpClient Class
  3. List<T> Class
  4. Asynchronous Programming with Async and Await

Points of Interest

In this article, I have demonstrated how you can use C# to develop cross-platform applications. There is no need to learn multiple languages to target multiple frameworks and application systems. You can use one single programming language, even C#, and write native applications on multiple platforms.

Although C# doesn’t execute natively, even on those platforms. Mono Runtime is responsible for executing the applications on those platforms. Just like .NET’s virtual machine or Windows Runtime executes C# code on Windows environments. On other platforms (and including Windows if compiling and using Mono), you can use Mono Runtime to target the platforms and make use of .NET libraries and lightweight programming model of C# programming language.

I hope you like this article, wait up for the next articles, or write back to me to get more. :-)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)