How to execute C# code?


In this chapter we are going to tell you that "how a code written in C# language is executed?". In the previous chapter we have told you that C# program can be written in Notepad as well as in Visual Studio 2010 IDE. So here we are going to explain the procedure of execution of C# code written in both Notepad and Visual Studio 2010 IDE one by one:


Execution of C# code written in Notepad


  • Write the following code in the Notepad:
  • using System;
    namespace SampleApplication
    {
    class Sample
    {
    static void Main(string[] args)
    { /* my first program in C# */
    Console.WriteLine("Sample Program");
    Console.ReadLine();
    }
    }
    }

  • Now save the above code in any location where you want to save it as "Sample.cs".
  • Now Go to Start->All Programs->Microsoft Visual Studio 2010->Visual Studio Tools->Visual Studio 2010 Command Prompt.
  • Now set the path of command prompt with the location where you saved your program.
  • Now compile your program by writing following command:
  • D:\> csc sample.cs

  • This will give some information about the version and .NET Framework.. If there is any error then it will produce the error message.
  • Now to run the application write the following command:
  • D:\>sample

  • This will produce the output as given below:
  • csharp-execute

Execution of C# code written in Visual Studio 2010 IDE


  • Open Microsoft Visual Studio 2010.
  • Now go to File->New Project.
  • This will open a "New Project dialog" box select Visual C# language and Console Application from the pane and give the name to the project as Sample and press OK.
  • Visual Studio 2010 IDE will open a editor with some previously written code remove that code and add the following code in that editor:
  • using System;
    namespace SampleApplication
    {
    class Sample
    {
    static void Main(string[] args)
    { /* my first program in C# */
    Console.WriteLine("Sample Program");
    Console.ReadLine();
    }
    }
    }

  • Now press F5 key this will give the following output:
  • csharp-execute