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:
- An identifier must begin with a letter, an underscore, or @, followed by a series of letters, digits ( 0 - 9 ), underscores ( _ ), and @.
- The first character of an identifier cannot be a digit.
- An identifier must not contain any embedded spaces or symbols, such as ? - +! # % ^ & * ( ) [ ] { } . ; : " ' / \.
- An identifier cannot be a C# keyword, unless it has an @ prefix. For example, @if is a valid identifier, but if is not, because if is a keyword.
- Identifiers are case-sensitive. Uppercase and lowercase letters are considered different letters.
- It must not be the same as a C# class library name.
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:
-
No Class or Method Needed: Top-level statements allow you to write code directly at the top level of a file without defining a class or method.
-
File as the Entry Point: A file containing top-level statements is treated as the entry point of the program, similar to the
Mainmethod. -
automatically
MainMethod: The compiler automatically generates aMainmethod, and treats the top-level statements as theMainbody of the method. -
Support for Local Functions: Even though no class needs to be defined, local functions can still be defined in a file with top-level statements.
-
Better Readability: For simple scripts or tools, top-level statements provide better readability and conciseness.
-
Suitable for Small Projects: Top-level statements are ideal for small projects or scripts, allowing code to be written and run quickly.
-
Compatible with Existing Code: Top-level statements can be used together with existing C# codebases without affecting existing code.
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
- **File restriction:** Top-level statements can be used in only one source file. If a project has multiple files using top-level statements, a compilation error will occur.
- **Program entry:** If top-level statements are used, the file implicitly contains a Main method, and that file becomes the entry point of the program.
- **Scope restriction:** Code in top-level statements shares a global scope, which means variables and methods defined in top-level statements can be accessed throughout the file.
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.