Introduction to C Sharp
C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. You can use C# to create Windows client applications, XML Web services, distributed components, client-server applications, database applications, and much, much more.
C# syntax simplifies many of the complexities of C++ and provides powerful features such as nullable value types, enumerations, delegates, lambda expressions and direct memory access.
Birds eye view of object-oriented support
As an object-oriented language, C# supports the concepts of encapsulation, inheritance, and polymorphism. All variables and methods, including the Main method, the applications entry point, are encapsulated within class definitions. A class may inherit directly from one parent class, but it may implement any number of interfaces. Methods that override virtual methods in a parent class require the override keyword as a way to avoid accidental redefinition. In C#, a struct is like a lightweight class; it is a stack-allocated type that can implement interfaces but does not support inheritance.
In addition to these basic object-oriented principles, C# makes it easy to develop software components through several innovative language constructs, including the following: 1. Encapsulated method signatures called delegates, which enable type-safe event notifications. 2. Properties, which serve as accessors for private member variables. 3. Attributes, which provide declarative metadata about types at run time. 4. Inline XML documentation comments. 5. Language-Integrated Query (LINQ) which provides built-in query capabilities across a variety of data sources.
Simple and flexible build process
The C# build process is simple compared to C and C++ and more flexible than in Java. There are no separate header files, and no requirement that methods and types be declared in a particular order. A C# source file may define any number of classes, structs, interfaces, and events.
What really happens under the hood?
Before exploring any programming language its quiet important to understand the build process and what happens under the scenes.
.NET Framework Platform Architecture
C# programs run on the .NET Framework, an integral component of Windows that includes a virtual execution system called the common language runtime (CLR) and a unified set of class libraries. The CLR is the commercial implementation by Microsoft of the common language infrastructure (CLI), an international standard that is the basis for creating execution and development environments in which languages and libraries work together seamlessly.
So for simplicity the CLR can be thought of as the JVM in the java world(they are not the same thing but makes the visualization easier). Source code written in C# is compiled into an intermediate language (IL) that conforms to the CLI specification. The IL code and resources, such as bitmaps and strings, are stored on disk in an executable file called an assembly, typically with an extension of .exe or .dll. An assembly contains a manifest that provides information about the assemblys types, version, culture, and security requirements.
(c# source file + resources + references) -> c# complier -> assembly(.exe or .dll) -> CLR(uses .NET Framework Class Libraries) -> Converted to machine code(used by OS)
When the C# program is executed, the assembly is loaded into the CLR, which might take various actions based on the information in the manifest. Then, if the security requirements are met, the CLR performs just in time (JIT) compilation to convert the IL code to native machine instructions. The CLR also provides other services related to automatic garbage collection, exception handling, and resource management.
Language interoperability
Language interoperability is a key feature of the .NET Framework. Because the IL code produced by the C# compiler conforms to the Common Type Specification (CTS), IL code generated from C# can interact with code that was generated from the .NET versions of Visual Basic, Visual C++, or any of more than 20 other CTS-compliant languages.
A single assembly may contain multiple modules written in different .NET languages, and the types can reference each other just as if they were written in the same language. In addition to the run time services, the .NET Framework also includes an extensive library of over 4000 classes organized into namespaces that provide a wide variety of useful functionality for everything from file input and output to string manipulation to XML parsing, to Windows Forms controls. The typical C# application uses the .NET Framework class library extensively to handle common “plumbing” chores.
Version confusion
The biggest problem when dealing with C#s version numbers is the fact that it is not tied to a version of the .NET Framework, which it appears to be due to the syncronized releases between Visual Studio and the .NET Framework. For instance, in VS2008 you can write C# 3.0 and target .NET Framework 2.0, 3.0 and 3.5. The C# 3.0 nomenclature describes the version of the code syntax and supported features in the same way that ANSI C89, C90, C99 describe the code syntax/features for C.
C# 1.0 with Visual Studio.NET(.NET 1.0)
C# 2.0 with Visual Studio 2005(.NET 2.0) First version to call Dispose on IEnumerators which implemented IDisposable. A few other small features.
C# 3.0 with Visual Studio 2008(.NET 3.5) Major new features: lambda expressions, extension methods, expression trees, anonymous types, implicit typing (var), query expressions
C# 4.0 with Visual Studio 2010(.NET 4) Major new features: late binding (dynamic), delegate and interface generic variance, more COM support, named arguments, tuple data type and optional parameters
C# 5.0 with Visual Studio 2012(.NET 4.5) Major features: async programming, caller info attributes. Breaking change: loop variable closure.
C# 6.0 with Visual Studio 2015(.NET 4.6) Features: initializers for automatically implemented properties, using directives to import static members, exception filters, indexed members and element initializers, await incatch and finally, extension Add methods in collection initializers.
Mono C# compiler
Mono is a free and open source project led by Xamarin, a subsidiary of Microsoft to create an Ecma standard-compliant, .NET Framework-compatible set of tools including, among others, a C# compiler and a Common Language Runtime.
What exactly is Mono?
When Microsoft unleashed .NET onto the world they were nice enough to hand the Common Language Infrastructure (CLI), along with the C# language, to the people at the European Computer Manufactures Association, better known to most as the ECMA. This allowed for an ECMA standards for the CLI and C# to be developed and, eventually, these ECMA standards also became ISO standards.
At this stage you might be thinking “So, what has this got to do with what Mono is?” Relax, slow down, Im getting to it. This standardization meant that details about how a CLI implementation should work, and also details about the C# programming language, where publicly available and anybody with the time and desire could implement their own CLI, essentially making their own version of .NET. Thus Mono was born.
Mono is an “open source development platform based on the .NET framework that allows developers to build Linux and cross-platform applications with unprecedented productivity”. At the time of writing this article the latest stable version of Mono is 1.0.5 and it provides the following features:
- A Common Language Runtime (CLR) that is compatible with the ECMA standard
- A C# compiler
- A set of class libraries
- Ancillary tools such as a disassembler, debugger, IDE, etc.
Although it may not sound like much to many, what the people behind the Mono project have achieved is quite impressive. The set of class libraries available with mono include implementations of ADO.NET, ASP.NET, and System.Windows.Forms as well as many other aspects of the BCL that .NET developers will be familiar with.
Added to this is the Gtk# library which is a fully featured library that allows for the development of GUI apps on top of the gtk+ toolkit. All in all, quite impressive.
With Mono you can develop and run .NET applications on Linux, Windows and other platforms. You can build and deploy ASP.NET application on Linux servers. You can even run applications that you compiled using the Microsoft C# compiler on the Mono runtime and vice versa.
Are .NET and Mono like Pikachu and Ash?
Yes fortunately they are best friends, meaning they are interoperable. You can simply take the assembly created by the Mono compiler (HelloWorld.exe in that example), double click on it in a Windows environment with .NET installed, and it would execute.
How exactly does that work? Well, its simple really. The Mono C# compiler, and the Microsoft C# compiler, compile code into an intermediary form known as IL. When you execute anassembly the runtime interprets and executes the IL code. So you can take an assembly compiled from VB.NET code, or any .NET language, and run it on Mono and vice versa. There is however one small issue with this; Mono doesnt have a complete implementation of the .NET class libraries so not all of your applications can be run using Mono.
Get C# up and running in MacOS
We will use the open source implemention Mono, to run C# scripts in MacOS.
Installation
$brew update
$brew install mono
Running HelloWorld!
To the most basic functionality available, copy the following code into a file called hello.cs.
using System;
public class HelloWorld
{
static public void Main ()
{
Console.WriteLine ("Hello World!");
}
}
To compile, use mcs: $mcs hello.cs
The compiler will create “hello.exe”, which you can run using: mono hello.exe
The program should run and output: Hello World!
REPL
C# interactive shell that is also a part of Mono’s C# compiler. An interactive shell is usually referred to as a read eval print loop or repl. The C# interactive shell is built on top of the Mono. CSharp library, a library that provides a C# compiler service that can be used to evaluate expressions and statements on the flight as well as creating toplevel types (classes, structures, enumerations).
To use the C# compiler in interactive mode, you need to start it with the the “csharp” command from the command line:
$ csharp
Mono C# Shell, type "help;" for help
Enter statements below.
csharp>