C# Basic Syntax

C# is an object-oriented programming language. In the object-oriented programming methodology, a program consists of various interacting objects. Objects of the same kind usually have the same type, or in other words, are in the same class.

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

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

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 Yourself »

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

Length: 4.5
Width: 3.5
Area: 15.75

usingKeywords

The first statement in any C# program is:

using System;

usingThe keyword is used to include a namespace in a program. A program can contain multiple using statements.

classKeywords

classThe keyword is used to declare a class.

Comments in C#

Comments are used to explain code. The compiler ignores comment entries. In C# programs, multi-line comments start with/*Start with the character*/Terminate, as shown below:

/* 这个程序演示
C# 的注释
使用 */

Single-line comments use//Symbol representation. For example:

// This line is a comment

Member variable

Variables are properties or data members of a class, used to store data. In the above program,RectangleThe class has two member variables namedlengthandwidth。

Member function

A function is a series of statements that perform a specified task. Member functions of a class are declared within the class. Our example class Rectangle contains three member functions: AcceptDetails、GetAreaandDisplay。

Instantiate a class

In the above program, the classExecuteRectangleis one that containsMain() Methods and instantiationRectangleThe class of the class.

Identifiers

Identifiers are used to identify classes, variables, functions, or any other user-defined items. In C#, naming must follow the following basic rules:

  • Identifiers must begin with a letter, underscore, or@Start with a letter, followed by a series of letters, digits (0 - 9), underscores (_), and @.
  • The first character in an identifier cannot be a digit.
  • Identifiers must not contain any embedded spaces or symbols, such as ? - +! # % ^ & * ( ) [ ] { } . ; : " ' / \.
  • Identifiers cannot be C# keywords, unless they have an @ prefix. For example, @if is a valid identifier, but if is not, because if is a keyword.
  • Identifiers must be case-sensitive. Uppercase and lowercase letters are considered different letters.
  • Must not be the same as C#'s class library names.

C# keywords

Keywords are predefined reserved words for the C# compiler. These keywords cannot be used as identifiers. However, if you want to use these keywords 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
abstractasbaseboolbreakbytecase
catchcharcheckedclassconstcontinuedecimal
defaultdelegatedodoubleelseenumevent
explicitexternfalsefinallyfixedfloatfor
foreachgotoifimplicitinin (generic
modifier)
int
interfaceinternalislocklongnamespacenew
nullobjectoperatoroutout
(generic
modifier)
overrideparams
privateprotectedpublicreadonlyrefreturnsbyte
sealedshortsizeofstackallocstaticstringstruct
switchthisthrowtruetrytypeofuint
ulonguncheckedunsafeushortusingvirtualvoid
volatilewhile
Contextual keywords
addaliasascendingdescendingdynamicfromget
globalgroupintojoinletorderbypartial
(type)
partial
(method)
removeselectset

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 needing to wrap them in methods or classes.

Features:

  • No class or method required: Top-level statements allow you to write code directly at the top level of a file without defining classes or methods.

  • File as entry point: A file containing top-level statements is treated as the program's entry point, similar to the previous C#.Mainmethod.

  • AutomaticMainMethods: The compiler automatically generates aMainmethod, and takes top-level statements asMainBody of the method.

  • Supports local functions: Although there is no need to define a class, 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 very suitable for small projects or scripts, allowing you to quickly write and run code.

  • Compatible with existing code: Top-level statements can be used 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, etc.

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 variable
Console.WriteLine($"{message} {number}.");

// define and call methods
int Add(int a, int b) => a + b;
Console.WriteLine($"Sum of 1 and 2 is {Add(1, 2)}.");

// use 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 restrictions:Top-level statements can only be used in one source file. If there are multiple files using top-level statements in a project, it will cause a compilation error.
  • Program entry:If top-level statements are used, the file implicitly contains a Main method, and the file becomes the program's entry point.
  • Scope limitations:Code in top-level statements shares a global scope, meaning variables and methods defined in top-level statements can be accessed throughout the entire file.

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

other extensions