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 in 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 being able to do everything that you can do on one platform, on another one too. C# can do the same, on every platform. The concept only requires modifying your compilers to be able to accept new environments, the same thing applies to C++ Java, and other similar high-level programming languages. C# also works similarly. 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 the 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 a virtual machine, which then translates the code using their metadata and other stuff 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, 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, and it managed to get the attention of developers from other platforms and systems too. Mono Project is one of such products that came up not shortly but had been known for a while. Mono Project was started to provide C# developers with a cross-platform experience. Mono Project can be installed on the following platforms.

  1. Windows.
  2. Linux: This counts any of the distributions 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, 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 another 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 a non-Windows environment and all by just using terminal or command-line commands to compile and use the application. I have learned a lot of things by using the terminal in the Linux environment, so I would also recommend you guys give it a try.

Installing Mono

Installing the Mono is different on different environments, on Windows and Mac, it is pretty much the same. All you have to do is download the installer and run it. It installs everything for you. But on 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 in all of the environments.

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.

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 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 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 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 effort into it.

Ubantu

Ubuntu Studio shows the list of IDEs.

Hello World

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,

  • 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 know in the .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 in a .NET environment. You all are already aware of the following code.

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.

Mono Develop

Pretty simple, right? But notice that this code now runs on a native Linux environment. There are no underground .NET frameworks supporting it. In reality, it is the Mono Runtime that 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.

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

namespace HelloWorld
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            // Create the list of 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 ran, please see below.

External Console

It just prints everything and then terminates. These were a few basic things. 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 to 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 the .NET framework. I will be using an object from this namespace and then I will call the functions to download the data from an online API and then I will print it.

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

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

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 a string and prints it. This shows, that C# not only just works in the console, but 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 models of C# programming language.

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


Recommended Free Ebook
Similar Articles