C Sharp TutorialC Sharp .NET Compiler Platform (Roslyn)C Sharp 3.0 FeaturesC Sharp 4.0 FeaturesC Sharp 5.0 FeaturesC Sharp 6.0 FeaturesC Sharp 7.0 FeaturesC Sharp Access ModifiersC Sharp Access network shared folder with username and passwordC Sharp Accessing DatabasesC Sharp Action FiltersC Sharp Aliases of built-in typesC Sharp an overview of collectionsC Sharp Anonymous typesC Sharp ArraysC Sharp ASP.NET IdentityC Sharp AssemblyInfo.cs ExamplesC Sharp Async-AwaitC Sharp Async/await, Backgroundworker, Task and Thread ExamplesC Sharp Asynchronous SocketC Sharp AttributesC Sharp Authentication handlerC Sharp BackgroundWorkerC Sharp BigIntegerC Sharp Binary SerializationC Sharp BindingListC Sharp Built-in TypesC Sharp CachingC Sharp CastingC Sharp Checked and UncheckedC Sharp CLSCompliantAttributeC Sharp Code ContractsC Sharp Code Contracts and AssertionsC Sharp Collection InitializersC Sharp Comments and regionsC Sharp Common String OperationsC Sharp Conditional StatementsC Sharp Constructors and FinalizersC Sharp Creating Own MessageBox in Windows Form ApplicationC Sharp Creational Design PatternsC Sharp Cryptography (System.Security.Cryptography)C Sharp Data AnnotationC Sharp DateTime MethodsC Sharp DelegatesC Sharp Dependency InjectionC Sharp DiagnosticsC Sharp Dynamic typeC Sharp EnumC Sharp Equality OperatorC Sharp Equals and GetHashCodeC Sharp EventsC Sharp Exception HandlingC Sharp Expression TreesC Sharp Extension MethodsC Sharp File and Stream I/OC Sharp FileSystemWatcherC Sharp Func delegatesC Sharp Function with multiple return valuesC Sharp Functional ProgrammingC Sharp Garbage Collector in .NETC Sharp Generating Random NumbersC Sharp Generic Lambda Query BuilderC Sharp GenericsC Sharp Getting Started: Json with C SharpC Sharp GuidC Sharp Handling FormatException when converting string to other typesC Sharp Hash FunctionsC Sharp ICloneableC Sharp IComparableC Sharp IDisposable interfaceC Sharp IEnumerableC Sharp ILGeneratorC Sharp ImmutabilityC Sharp Implementing Decorator Design PatternC Sharp Implementing Flyweight Design PatternC Sharp Import Google ContactsC Sharp Including Font ResourcesC Sharp IndexerC Sharp InheritanceC Sharp Initializing PropertiesC Sharp INotifyPropertyChanged interfaceC Sharp InterfacesC Sharp InteroperabilityC Sharp IQueryable interfaceC Sharp IteratorsC Sharp KeywordsC Sharp Lambda expressionsC Sharp Lambda ExpressionsC Sharp LINQ QueriesC Sharp LINQ to Objects

C Sharp Tutorial

From WikiOD

C# is a multi-paradigm, C-descendant programming language from Microsoft. C# is a managed language that compiles to CIL, intermediate bytecode which can be executed on Windows, Mac OS X and Linux.

Versions 1.0, 2.0 and 5.0 were standardized by ECMA (as ECMA-334), and standardization efforts for modern C# are underway.

Versions[edit | edit source]

Version Release Date
1.0 2002-01-01
1.2 2003-04-01
2.0 2005-09-01
3.0 2007-08-01
4.0 2010-04-01
5.0 2013-06-01
6.0 2015-07-01
7.0 2017-03-07

Creating a new console application (Visual Studio)[edit | edit source]

  1. Open Visual Studio
  2. In the toolbar, go to File -> New Project
  3. Select the Console Application project type
  4. Open the file Program.cs in the Solution Explorer
  5. Add the following code to Main():
public class Program
    public static void Main()
        // Prints a message to the console.
        System.Console.WriteLine("Hello, World!");

        /* Wait for the user to press a key. This is a common
           way to prevent the console window from terminating
           and disappearing before the programmer can see the contents
           of the window, when the application is run via Start from within VS. */
  • In the toolbar, click Debug -> Start Debugging or hit F5 or ctrl + F5 (running without debugger) to run the program.

Live Demo on ideone

Explanation[edit | edit source]

  • class Program is a class declaration. The class Program contains the data and method definitions that your program uses. Classes generally contain multiple methods. Methods define the behavior of the class. However, the Program class has only one method: Main.
  • static void Main() defines the Main method, which is the entry point for all C# programs. The Main method states what the class does when executed. Only one Main method is allowed per class.
  • System.Console.WriteLine("Hello, world!"); method prints a given data (in this example, Hello, world!) as an output in the console window.
  • System.Console.ReadKey(), ensures that the program won't close immediately after displaying the message. It does this by waiting for the user to press a key on the keyboard. Any key press from the user will terminate the program. The program terminates when it has finished the last line of code in the main() method.

Using the command line[edit | edit source]

To compile via command line use either MSBuild or csc.exe (the C# compiler), both part of the Microsoft Build Tools package.

To compile this example, run the following command in the same directory where HelloWorld.cs is located:

%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\csc.exe HelloWorld.cs

It can also be possible that you have two main methods inside one application. In this case, you have to tell the compiler which main method to execute by typing the following command in the console.(suppose Class ClassA also has a main method in the same HelloWorld.cs file in HelloWorld namespace)

%WINDIR%\Microsoft.NET\Framework64\v4.0.30319\csc.exe HelloWorld.cs /main:HelloWorld.ClassA

where HelloWorld is namespace

Note: This is the path where .NET framework v4.0 is located in general. Change the path according to your .NET version. In addition, the directory might be framework instead of framework64 if you're using the 32-bit .NET Framework. From the Windows Command Prompt, you can list all the csc.exe Framework paths by running the following commands (the first for 32-bit Frameworks):

dir %WINDIR%\Microsoft.NET\Framework\csc.exe /s/b
dir %WINDIR%\Microsoft.NET\Framework64\csc.exe /s/b

Compiling the .cs file

There should now be an executable file named HelloWorld.exe in the same directory. To execute the program from the command prompt, simply type the executable's name and hit Enter as follows:


This will produce:

Hello, world!

Executing the exe file in the console

You may also double click the executable and launch a new console window with the message "Hello, world!"

Running the executable and using double click

Creating a new project in Visual Studio (console application) and Running it in Debug mode[edit | edit source]

Download and install Visual Studio. Visual Studio can be downloaded from VisualStudio.com. The Community edition is suggested, first because it is free, and second because it involves all the general features and can be extended further.

Open Visual Studio.

Welcome. Go to File -> New -> Project.

Microsoft Visual Studio - File Menu

Click Templates -> Visual C# -> Console Application

Microsoft Visual Studio - New Project window

After selecting Console Application, Enter a name for your project, and a location to save and press OK. Don't worry about the Solution name.

Project created. The newly created project will look similar to:

Microsoft Visual Studio - c# Default Project

(Always use descriptive names for projects so that they can easily be distinguished from other projects. It is recommended not to use spaces in project or class name.)

Write code. You can now update your Program.cs to present "Hello world!" to the user.

using System;

namespace ConsoleApplication1
    public class Program
        public static void Main(string[] args)

Add the following two lines to the public static void Main(string[] args) object in Program.cs: (make sure it's inside the braces)

Console.WriteLine("Hello world!");

Why Console.Read()? The first line prints out the text "Hello world!" to the console, and the second line waits for a single character to be entered; in effect, this causes the program to pause execution so that you're able to see the output while debugging. Without Console.Read();, when you start debugging the application it will just print "Hello world!" to the console and then immediately close. Your code window should now look like the following:

using System;

namespace ConsoleApplication1
    public class Program
        public static void Main(string[] args)
            Console.WriteLine("Hello world!");

Debug your program. Press the Start Button on the toolbar near the top of the window Start Debugging Button or press F5 on your keyboard to run your application. If the button is not present, you can run the program from the top menu: Debug -> Start Debugging. The program will compile and then open a console window. It should look similar to the following screenshot:

Console running the Hello World application

  • Stop the program. To close the program, just press any key on your keyboard. The Console.Read() we added was for this same purpose. Another way to close the program is by going to the menu where the Start button was, and clicking on the Stop button.

Creating a new program using Mono[edit | edit source]

First install Mono by going through the install instructions for the platform of your choice as described in their installation section.

Mono is available for Mac OS X, Windows and Linux.

After installation is done, create a text file, name it HelloWorld.cs and copy the following content into it:

public class Program
    public static void Main()
        System.Console.WriteLine("Hello, world!");
        System.Console.WriteLine("Press any key to exit..");

If you are using Windows, run the Mono Command Prompt which is included in the Mono installation and ensures that the necessary environment variables are set. If on Mac or Linux, open a new terminal.

To compile the newly created file, run the following command in the directory containing HelloWorld.cs:

mcs -out:HelloWorld.exe HelloWorld.cs

The resulting HelloWorld.exe can then be executed with:

mono HelloWorld.exe

which will produce the output:

Hello, world!   
Press any key to exit..

Creating a new program using .NET Core[edit | edit source]

First install the .NET Core SDK by going through the installation instructions for the platform of your choice:

After the installation has completed, open a command prompt, or terminal window.

Create a new directory with mkdir hello_world and change into the newly created directory with cd hello_world.

Create a new console application with dotnet new console.

This will produce two files:


<Project Sdk="Microsoft.NET.Sdk">




using System;

namespace hello_world
    class Program
        static void Main(string[] args)
            Console.WriteLine("Hello World!");

Restore the needed packages with dotnet restore.

Optional Build the application with dotnet build for Debug or dotnet build -c Release for Release. dotnet run will also run the compiler and throw build errors, if any are found.

Run the application with dotnet run for Debug or dotnet run .\bin\Release\netcoreapp1.1\hello_world.dll for Release.

Command Prompt output[edit | edit source]


Creating a new query using LinqPad[edit | edit source]

LinqPad is a great tool that allows you to learn and test features of .Net languages (C#, F# and VB.Net.)

Install LinqPad

Create a new Query (Ctrl + N) Getting_started_with_C_Sharp_Language

Under language, select "C# statements" Getting_started_with_C_Sharp_Language

Type the following code and hit run (F5)

string hw = "Hello World";

hw.Dump(); //or Console.WriteLine(hw);


  • You should see "Hello World" printed out in the results screen. Getting_started_with_C_Sharp_Language
  • Now that you have created your first .Net program, go and check out the samples included in LinqPad via the "Samples" browser. There are many great examples that will show you many different features of the .Net languages. Getting_started_with_C_Sharp_Language


  1. If you click on "IL", you can inspect the IL code that your .net code generates. This is a great learning tool. Getting_started_with_C_Sharp_Language
  2. When using LINQ to SQL or Linq to Entities you can inspect the SQL that's being generated which is another great way to learn about LINQ.

Creating a new project using Xamarin Studio[edit | edit source]

  1. Download and install Xamarin Studio Community.
  2. Open Xamarin Studio.
  3. Click File → New → Solution.

Creating New Project in Xamarin Studio

  • Click .NET → Console Project and choose C#.
  • Click Next to proceed.

Choosing Template for new project

  • Enter the Project Name and Browse... for a Location to Save and then click Create.

Project name and location

  • The newly created project will look similar to:


  • This is the code in the Text Editor:
using System;

namespace FirstCsharp
    public class MainClass
        public static void Main(string[] args)
            Console.WriteLine("Hello World!");
  • To run the code, press F5 or click the Play Button as shown below:

Run the code

  • Following is the Output: