Using C# For Cross-Platform Development

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:

diagram

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

The assemblies are sent to virtual machine, who 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 a 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 distribution 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 starting

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 the 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 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, and 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.

ubantu
               Ubuntu Studio showing the list of IDEs.

Hello world
                                             Hello world project opened in Mono Project.

In the next step, I will share a few example 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,

  • Visual Studio Community
  • Mono Project — Official Website
  • 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. You all are already aware of the following code,

  1. using System;  
  2. using System.Net.Http;  
  3. namespace HelloWorld  
  4. {  
  5.     class MainClass  
  6.     {  
  7.         public static void Main(string[] args)  
  8.         {  
  9.             Console.WriteLine("Hello, who's there?");  
  10.             string name = "";  
  11.             name = Console.ReadLine();  
  12.             Console.WriteLine(string.Format("Hello {0} from Linux using C#.", name));  
  13.         }  
  14.     }  
  15. }  
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.

monodevlop

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.
  1. using System;  
  2. using System.Net.Http;  
  3. using System.Collections.Generic;  
  4. namespace HelloWorld  
  5. {  
  6.     class MainClass  
  7.     {  
  8.         public static void Main(string[] args)  
  9.         {  
  10.             // Create the list of the people.  
  11.             var people = new List < Person > ();  
  12.             people.Add(new Person  
  13.             {  
  14.                 Name = "Afzaal Ahmad Zeeshan", Age = 20  
  15.             });  
  16.             people.Add(new Person  
  17.             {  
  18.                 Name = "Sofiya Zeeshan", Age = 19  
  19.             });  
  20.             people.Add(new Person  
  21.             {  
  22.                 Name = "Daniyal Ahmad Rizwan", Age = 15  
  23.             });  
  24.             people.Add(new Person  
  25.             {  
  26.                 Name = "Eminem", Age = 43  
  27.             });  
  28.             // Printing the details for people.  
  29.             foreach(var person in people)  
  30.             {  
  31.                 Console.WriteLine(person);  
  32.             }  
  33.         }  
  34.     }  
  35.     class Person  
  36.     {  
  37.         // Provide the attributes.  
  38.         public string Name  
  39.         {  
  40.             get;  
  41.             set;  
  42.         }  
  43.         public int Age  
  44.         {  
  45.             get;  
  46.             set;  
  47.         }  
  48.         // Override the default ToString  
  49.         public override string ToString()  
  50.         {  
  51.             return string.Format("[Person: Name={0}, Age={1}]", Name, Age);  
  52.         }  
  53.     }  
  54. }  
How this code actually ran, please see below.

console

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,
  1. using System;  
  2. using System.Net.Http;  
  3. using System.Collections.Generic;  
  4. namespace HelloWorld  
  5. {  
  6.     class MainClass  
  7.     {  
  8.         public static void Main(string[] args)  
  9.         {  
  10.             downloadAndPrint();  
  11.         }  
  12.         private static void downloadAndPrint()  
  13.         {  
  14.             System.Threading.Tasks.Task.Run(async() =>  
  15.             {  
  16.                 using(var client = new HttpClient())  
  17.                 {  
  18.                     Console.WriteLine("Downloading the data...");  
  19.                     var message = await client.GetStringAsync("http://afzaalahmadzeeshan.gear.host/api/sample");  
  20.                     Console.WriteLine();  
  21.                     Console.WriteLine(message);  
  22.                 }  
  23.             }).Wait();  
  24.             Console.WriteLine("Exiting the function..");  
  25.         }  
  26.     }  
  27. }  
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.

console

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.

Up Next
    Ebook Download
    View all
    Learn
    View all