The tutorial "Starting with C# Program" will help to get start with C#. Below are some of the key takeaways of this chapter:
To understand the basic syntax of a C# program.
What is a Namespace?
What is a Class?
What is a Main method?
How to execute first application?
Syntax
Example
Below example is a simple C# program.
[csharp]
using System;
using System.Collection.Generics;
using System.Text;
namespace SPLessons
{
class Program
{
static void Main(string[] args)// Main begins program execution.
{
Console.WriteLine("SPLessons C# Sharp Tutorial!"); // Line1: Write to console
Console.ReadLine(); // Line2:ReadLine-Wait’s for user Input
}
}
}
[/csharp]
Output:
Steps to compile a program
Description
Compiling and Executing: Use key F5 to execute the program.
Open a Text Editor and add the above-mentioned code.
Save the file as Hello.cs.
Open the command prompt tool and go to the directory where the file is saved.
Type csc Hello.cs and press Enter to compile your code.
Hello.exe executable file is generated.
Type Hello to execute the program.
Output "Hello World" printed on the screen can be seen.
Note
The ReadLine command tells the application to wait for an input from the user, and the console window now allows to enter the text. Press Enter to close it.
Package
Description
A program generally has multiple using statements. Here, 3 namespaces are provided that are imported.
class
Description
Class is a blueprint of objects. It is a collection of methods,member variables, etc.
Main Class
Description
Here the execution of the program starts.
static void Main(string[] args)
static : The static keyword tells that this method should be accessible without instantiating the class.
void : It is a return type which tells what will be the result returned to the method.
int returns integer values.
string returns text values.
void does not return a value.
Main: This method is the entry-point of application, i.e. where the execution of the program starts.
Arguments passed in the main class are of type string(string[] args)
Note
C# is case sensitive.
All statements and expression must end with a semicolon (;).
The execution starts at the Main method.
Unlike Java, the name of the program file could be different from the class name.