C# Syntax

C# Syntax

In this tutorial, you’ll learn about the basic C# syntax, including compilation, whitespace, statements, identifiers, keywords, literals, and comments.

C# syntax is inspired by C and C++ syntax. And it has similar syntax with Java as well.

 

C# Compilation and Execution of a C# Program

01. Compilation manually

The name of the C# compiler is csc.exe.

You can run csc manually from the command line to compile manually.

The following command compiles the Main.cs file

  • csc Main.cs: This produces an application named Main.exe.

To produce a library (.dll), do the following: csc /target:library Main.cs

Example:

Compile a C# program by using the command-line instead of the Microsoft Visual Studio IDE −

  • Open a text editor and add the above-mentioned code.
  • Save the file as helloworld.cs
  • Open the command prompt tool and go to the directory where you saved the file.
  • Type csc helloworld.cs and press enter to compile your code.
  • If there are no errors in your code, the command prompt takes you to the next line and generates helloworld.exe executable file.
  • Type helloworld to execute your program.
  • You can see the output Hello World printed on the screen.
02. Compilation of a C# Program via Microsoft Visual Studio IDE

To compile and execute a program in C#, you just need to click the Run button or press F5 key to execute the project in Microsoft Visual Studio IDE.

 

Whitespace

Whitespace refers to the characters that do not have visible output, including:

  • Carriage return
  • Space
  • New Line
  • Tab

C# compiler ignores whitespace. But you use whitespace to make the code readable.

For example, the C# compiler will treat the following code snippets the same despite their differences in the presentation:

with whitespace:

// with whitespace
bool isLight = false;

if (isLight)
{
    website.EnableLightMode();
}

without whitespace:

bool isLight = false; 
if (isLight){ website.EnableLightMode();}

 

Statements

A statement is a source code instruction that declares a type or instructs the program to do something. A simple statement is terminated by a semicolon (;).

For example, the following code has two simple statements:

int age = 9;
Console.WriteLine("Welcome to C#");

The first statement defines an integer variable and initializes its values to 9. The second statement prints out a message to the console window.

 

Blocks

A block is a sequence of zero or more statements. A block starts with an opening curly brace ({) and ends with a closing curly brace (}).

For example, you can group the two statements above into a block like this:

{
    int age = 9;
    Console.WriteLine("Welcome to C#");
}

Unlike a statment, a block does not require a semicolon (;).

 

Identifiers

In programming languages, identifiers are used for identification purposes. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name, or label. 

For example:

public class XDevSpace {
    static public void Main () 
    {
          int x;
    }
}

Here the total number of identifiers present in the above example is 3 and the names of these identifiers are: 

  • XDeevSpace: Name of the class
  • Main: Method name
  • x: Variable name

The identifier names follow these rules:

  • The only allowed characters for identifiers are all alphanumeric characters([A-Z], [a-z], [0-9]), '_' (underscore).
  • Identifiers should not start with digits([0-9])
  • Identifiers should not contain white spaces.
  • Identifiers are not allowed to use as keywords unless they include @ as a prefix. For example, @as is a valid identifier, but "as" is not because it is a keyword.
  • C# identifiers allow Unicode Characters.
  • C# identifiers are case-sensitive. For example: counter and Counter identifiers are different.
  • C# identifiers cannot contain more than 512 characters.

 

C# Keywords

In c#, Keywords are differentiated into two types those are:

  • Reserve Keywords
  • Contextual Keywords
01. C# Reserved keywords

Reserved keywords in C# are reserved for the compiler in any part of the program.

The following table lists the available reserved keywords in the c# programming language.

abstractboolcontinuedecimaldefault
eventexplicitexterncharchecked
classconstbreakasbase
delegateislocklongnum
bytecasecatchfalsefinally
fixedfloatforasforeach
gotoifimplicitinint
interfaceinternaldodoubleelse
namespacenewnullobjectoperator
outoverrideparamsprivateprotected
publicreadonlysealedshortsizeof
refreturnsbytestackallocstatic
stringstructvoidvolatilewhile
truetryswitchthisthrow
uncheckedunsafeushortusingstatic
virtualtypeofuintulongout
02. C# Contextual keywords

In c#, Contextual keywords can be used as an identifier in a limited program context, which can be outside of the context.

The following table lists the available Contextual Keywords in the c# programming language.

addaliasasyncawaitdynamic
fromgetorderbyascendingdescending
groupintojoinletnameof 
globalpartialsetremoveselect 
valuevarwhenWhereyield

 

Avoiding conflicts

To use a keyword as an identifier, qualify it with the @ prefix.
For instance:

class class {...} // Illegal 

class @class {...} // Legal

We cannot use class as the name of a class directly, we have to add the @ before it.
The @ symbol is not part of the identifier itself. So @myVariable is the same as myVariable.
The @ prefix is useful when using libraries written in other .NET languages that have different keywords.

 

Literals

Literals are primitive values in the program. For example, an integer has the following literal:

20

To form a string, you place the text inside the double quotes (") like this:

"Hello From X.DevSpace.com"

C# Comments

C# offers two different styles of source-code documentation: single-line comments, and multiline comments and XML Comments.

01. C# Single-line comments

A single-line comment begins with a double forward slash and continues until the end of the line.

For example:

int x = 7;   // Comment about assigning 7 to x
 
02. C# Multiline comments

A multiline comment begins with /* and ends with */.

For example:

int x = 1;   /* This is a comment that
                spans two lines        */
C# XML Comments

In c#, the XML Comments are defined by using /// (triple forward slashes) and with XML formatted comment body.

For example:

///<summary>
/// This class does something.
///</summary>

public class SomeClass
{
}

The documentation comments contain XML text used to make the program documentation.

The documentation starts with three contiguous forward slashes (///).

C# Notes:

  • C# compiler ignores whitespace such as carriage return, space, newline, and tab.
  • A simple statement is terminated with a semicolon (;). A block starts and ends with a pair of matching curly braces ({}).
  • C# identifers are case-sensitive.
  • C# supports single-line (//...), delimited comments (/*...*/), and documenation comments (///).