Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C# Basic Syntax

C# Basic Syntax

C# is an object-oriented programming language. In the object-oriented programming approach, a program consists of various objects that interact with each other. Objects of the same kind usually have the same type, that is, they are in the same class.

For example, take a Rectangle object. It has length and width properties. By design, it may need to accept these property values, calculate the area, and display details.

Let's look at the implementation of a Rectangle class and use it to discuss the basic syntax of C#:

Example

using

System

;

namespace

RectangleApplication

{

   

class

Rectangle

   

{

       

// Member variables

       

double

length

;

       

double

width

;

       

public

void

Acceptdetails

(

)

       

{

            length

=

4.5

;

   

            width

=

3.5

;

       

}

       

public

double

GetArea

(

)

       

{

           

return

length

width

;

       

}

       

public

void

Display

(

)

       

{

            Console

.

WriteLine

(

"Length: {0}"

, length

)

;

            Console

.

WriteLine

(

"Width: {0}"

, width

)

;

            Console

.

WriteLine

(

"Area: {0}"

, GetArea

(

)

)

;

       

}

   

}

   

   

class

ExecuteRectangle

   

{

       

static

void

Main

(

string

[

]

args

)

       

{

            Rectangle r

=

new

Rectangle

(

)

;

            r

.

Acceptdetails

(

)

;

            r

.

Display

(

)

;

            Console

.

ReadLine

(

)

;

       

}

   

}

}

Try it »

When the code above is compiled and executed, it produces the following result:


Length: 4.5
Width: 3.5
Area: 15.75

using The keyword

The first statement in any C# program is:


using System;

using The keyword is used to include namespaces in a program. A program can contain multiple using statements.

class The keyword

class The keyword is used to declare a class.

Comments in C#

Comments are used to explain code. The compiler ignores comment entries. In C#, multi-line comments begin with /* and end with the characters */, as shown below:


/* This program demonstrates
C# 的注释
使用 */

Single-line comments are denoted by the // symbol. For example:


// This line is a comment

Member Variable

Variables are properties or data members of a class, used to store data. In the program above,Rectangle The class has two member variables named length and width。

member function

A function is a series of statements that perform a specified task. A member function of a class is declared within the class. Our example class Rectangle contains three member functions: * AcceptDetails*,GetArea and Display。

Instantiating a Class

In the program above, the class ExecuteRectangle is one that contains the *Main() * method and instantiates Rectangle the class.

Identifiers

An identifier is used to identify a class, variable, function, or any other user-defined item. In C#, the naming of classes must follow these basic rules:

C# Keywords

Keywords are reserved words predefined by the C# compiler. These keywords cannot be used as identifiers, but if you want to use them as identifiers, you can prefix the keyword with the @ character.

In C#, some keywords have special meaning in the context of code, such as get and set; these are called contextual keywords.

The following table lists the reserved keywords and contextual keywords in C#:

Reserved Keywords
abstract
catch
default
explicit
foreach
modifier)
interface
null
 (generic       
 modifier) | override | params |

| private | protected | public | readonly | ref | return | sbyte | | sealed | short | sizeof | stackalloc | static | string | struct | | switch | this | throw | true | try | typeof | uint | | ulong | unchecked | unsafe | ushort | using | virtual | void | | volatile | while | | | | | | | Contextual Keywords | | add | alias | ascending | descending | dynamic | from | get | | global | group | into | join | let | orderby | partial
(type) | | partial
(method) | remove | select | set | | | |

Top-Level Statements

In C# 9.0, the concept of top-level statements was introduced. This is a new programming paradigm that allows developers to write statements directly at the top level of a file without encapsulating them in methods or classes.

Characteristics:

Traditional C# Code - Before using top-level statements, you had to write a C# program like this:

Example

using

System

;

namespace

MyApp

{

   

class

Program

   

{

       

static

void

Main

(

string

[

]

args

)

       

{

            Console

.

WriteLine

(

"Hello, World!"

)

;

       

}

   

}

}

C# Code Using Top-Level Statements - With top-level statements, it can be simplified to:

Example

using

System

;

Console

.

WriteLine

(

"Hello, World!"

)

;

Top-level statements support all common C# syntax, including declaring variables, defining methods, handling exceptions, and more.

Example

using

System

;

using

System.Linq

;

// Variable declarations in top-level statements

int

number

=

42

;

string

message

=

"The answer to life, the universe, and everything is"

;

// Output variables

Console

.

WriteLine

(

$

"{message} {number}."

)

;

// Define and call a method

int

Add

(

int

a,

int

b

)

=>

a

b

;

Console

.

WriteLine

(

$

"Sum of 1 and 2 is {Add(1, 2)}."

)

;

// Using LINQ

var

numbers

=

new

[

]

{

1

,

2

,

3

,

4

,

5

}

;

var

evens

=

numbers

.

Where

(

n

=>

n

%

2

==

0

)

.

ToArray

(

)

;

Console

.

WriteLine

(

"Even numbers: "

string

.

Join

(

", "

, evens

)

)

;

// Exception handling

try

{

   

int

zero

=

0

;

   

int

result

=

number

/

zero

;

}

catch

(

DivideByZeroException ex

)

{

    Console

.

WriteLine

(

"Error: "

ex

.

Message

)

;

}

Notes

Top-level statements have significant advantages in simplifying code structure, reducing learning difficulty, and speeding up development, making them especially suitable for writing simple programs and scripts.