The Anatomy of a Basic C# Application                              

C# demands that all program logic be contained within a type definition.  Recall that a type is a term that refers
to a class, interface, structure, enumeration, or delegate.  Unlike C++, it is not possible to create global functions
or global points of data in C#. All logic must be within a type definition.   

Every C# application must contain a class defining a Main() method that provides the entry point for the
application.  A Main() method must be declared static, which will be formally defined later.  

In its simplest form, a C# application can be defined as follows:


// C# source files end with a *.cs file extension.
using System;

class HelloWorld
{
  static void Main()
  {
     Console.WriteLine("Hello World!");        
  }
}



C# accepts other variations of Main():


// No return, no arguments.
static void Main()
{
  // Do stuff.
}



// No return, no arguments.

static void Main()
{
  // Do stuff.
}



// Integer return type, no arguments.

static int Main()
{
  // Do stuff.

  // Return an integer to the system. By convention, returning 0
  // indicates success. Anything else indicates an error code.
  return 0;
}



// Integer return type, get command line args.

static int Main(string[] args)
{
  // Process command line arguments.
  // Do stuff.
  // Return a value to the system.
  return 0;
}


This example processes the command line arguments passed into Main() as a string array called args.


class HelloWorld
{
  static int Main(string[] args)
  {

     // Do we have any arguments?

     for(int x = 0; x < args.Length; x++)
     {
        Console.WriteLine("Arg: {0}", args[x]);
     }
                                       
     Console.WriteLine("Hello World!");
     return 0;
  }
}


Also be aware that Main() can be declared public or private.  In fact, given that private is the default access
modifier in C# for type member, each of the Main() methods you just examined were in fact private.
The Anatomy of a Basic C# Application
Table of Contents
C# Tutorial | C#.NET Tutorial | C# Fundamental Tutorial

Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used
exclusively as an online learning aid.  Any attempts to copy, reproduce, or use for training is
strictly prohibited.
Courseware
Training Resources
Tutorials
Services