SoFunction
Updated on 2025-03-06

Introduction to the basics of C# language introduction

Preface:

C# (pronounced "See Sharp") is a new programming language that is not only object-oriented but also type-safe. Developers use C# to generate a variety of safe and reliable applications running in .NET. C# originated from the C language series, and C, C++, Java and JavaScript programmers will be able to get started soon. This tutorial provides an overview of the main components of the language in C# 8 and later.

C# is an object-oriented, component-oriented programming language. C# provides language constructs to directly support these concepts, making C# a very natural language for creating and using software components. Since its inception, C# has added features to support new workloads and emerging software design practices. C# is essentially an object-oriented language. _* You need to define the type and its behavior.

Several C# features help create reliable and durable applications. Garbage collection automatically recycles memory occupied by unused objects that are not accessible. A type that can be null prevents variables that do not reference assigned objects. Exception handling provides a structured and scalable method for error detection and recovery.Lambda Expressions support function programming technology. Language Integrated Query (LINQ) syntax creates a common pattern for processing data from any source. Asynchronous operation language supports syntax for building distributed systems. C# has a unified type system. All C# types (includingint anddouble All primitive types) inherit from a root object type. All types share a common set of operations. Values ​​of any type can be stored, transferred and processed consistently. In addition, C# also supports user-defined reference types and value types. C# allows dynamic allocation of lightweight structured objects and embedded storage. C# supports generic methods and types, thus enhancing type safety and performance. C# can provide iterators that enable the implementor of collection classes to define custom behaviors of client code.

C# emphasizes version control to ensure that programs and libraries change over time in a compatible way. The aspects directly affected by version control enhancement in C# design include: separatevirtual andoverride Modifiers, rules for method overload decisions, and support for explicit interface member declarations.

1. .NET architecture

C# programs run on .NET, which is a virtual execution system and a set of class libraries called the Common Language Runtime (CLR). CLR is the implementation of Microsoft's international standard for the Public Language Infrastructure (CLI). The CLI is the basis for creating execution and development environments where languages ​​and libraries work seamlessly.

Source code written in C# is compiled into an intermediate language (IL) that complies with the CLI specification. IL code and resources (such as bitmaps and strings) are stored in assemblies with a typically .dll extension. An assembly contains a list of types, versions, and cultures of the assembly.

When executing a C# program, the assembly is loaded into the CLR. CLR directly executes real-time (JIT) compilation, converting IL code to the local instructions. CLR can provide other services related to automatic garbage collection, exception handling, and resource management. Code executed by CLR is sometimes called "managed code". "Unmanaged code" is compiled into a platform-specific native language.

Language interoperability is an important feature of .NET. The IL code generated by the C# compiler complies with the Public Type Specification (CTS). IL code generated through C# can interact with code generated through .NET versions of F#, Visual Basic, and C++. There are more than 20 languages ​​compatible with CTS. A single assembly can contain multiple modules written in different .NET languages. These types can be referenced to each other as if they were written in the same language.

In addition to runtime services, .NET also contains a large number of libraries. These libraries support a variety of different workloads. They have been sorted into namespaces that provide a variety of practical features. These features include file input and output, string control, XML analysis, Web application framework, and Windows Forms controls. Typical C# applications widely use .NET class libraries to handle common "pipeline" pieces of work.

2. Hello world

“Hello, World”Programs have traditionally been used to introduce programming languages.

The C# code for this program is shown below:

using System;

class Hello
{
    static void Main()
    {
        ("Hello, World");
    }
}


“Hello, World”The program begins with referencesSystem The using directive for the namespace. Namespaces provide a hierarchical method for organizing C# programs and libraries. Namespaces contain types and other namespaces. For example,System Namespaces contain many types (such as the Console class referenced in the program) and many other namespaces (such as IO andCollections). With the use directive that references a given namespace, the type that is a member of the corresponding namespace can be used in a non-qualified manner. Because of the use directive, the program can use it As abbreviation of .

“Hello, World”The Hello class declared by the program has only one member, namely the Main method. The Main method is declared using the static modifier. Instance methods can use the keyword this to refer to a specific enclosed object instance, while static methods can be run without referencing a specific object. As agreed,Main A static method is the entry point of a C# program.

The output of the program is from the System namespaceConsole ClassicWriteLine Method generation. This class is provided by the standard class library. By default, the compiler automatically references the standard class library.

III. Types and variables

Type defines the structure and behavior of any data in C#. A declaration of a type can contain its members, base types, interfaces it implements, and operations allowed by the type. A variable is a tag used to refer to an instance of a specific type.

There are two types of C#: value type and reference type. Variables of value types directly contain their data. A variable of a reference type stores a reference to the data (called "objects"). For reference types, two variables can refer to the same object; operations performed on one variable may affect the object referenced by the other variable. With value types, each variable has its own copy of the data; therefore, operations performed on one variable do not affect another variable (except for ref and out parameter variables).

The identifier is the variable name. The identifier does not contain any spacesunicode Character sequence. If the identifier is prefixed with @, the identifier can be a C# reserved word. Using reserved words as identifiers is useful when interacting with other languages.

The value types of C# are further divided into: simple types, enumeration types, structure types, and can benull value type and tuple value type. C# reference types are further subdivided into class types, interface types, array types and delegate types.

C# programs use Type Declaration to create a new type. The type declaration specifies the name and member of the new type. Users can define the following six C# types: class type, structure type, interface type, enum type, delegate type, and tuple value type. Can also declarerecord type(record struct or record class). The record type has compiler synthesis members. Records are mainly used to store values ​​and have the least association behavior.

class Type defines a data structure that contains data members (fields) and function members (methods, properties, and others). Class types support single inheritance and pleomorphism, i.e., the mechanism by which derived classes can be extended and specifically targeted at base classes.
The struct type defines a structure that contains data members and function members, which is similar to a class type. However, unlike classes, structures are value types and usually do not require heap allocation. Structure types do not support user-specified inheritance, and all structure types are implicitly inherited from the typeobject
The interface type defines a contract as a group of named public members. accomplishinterface ofclass orstruct The implementation code of the interface member must be provided.interface It can be inherited from multiple base interfaces, and class and struct can implement multiple interfaces.
The delegate type represents a method that references a specific parameter list and return type. Through delegates, methods can be treated as entities that can be assigned to variables and passed as parameters. Delegation is the same as the function type provided by functional languages. They are also similar to the concept of "function pointer" that exists in some other languages. Unlike function pointers, delegates are object-oriented and type-safe.
classstructinterface anddelegate Types all support generics, so they can be parameterized using other types.

C# supports any type of one-dimensional and multi-dimensional arrays. Unlike the above types, array types can be used without declaring them first. Instead, array types are constructed by adding square brackets after the type name. For example, int[] is a one-dimensional array of type int, int[,] is a two-dimensional array of type int, and int[][] is a one-dimensional array of type int or a "interleaved" array.

Types that can be null do not need to be defined separately. For all types T that cannot be null, there is a corresponding type T? that can be null, which can contain an additional value null. For example, int? is a type that can hold any 32-bit integer or null value, and string? is a type that can hold any string or null value.

C# adopts a unified type system, so values ​​of any type can be regarded as objects. Each C# type is derived directly or indirectly from the object class type, and object is the final base class for all types. Just treat the value of the reference type as an object. Values ​​of value types can be treated as objects by performing boxing and unboxing operations. In the following example, the int value is converted to object and then restored to int.

int i = 123;
object o = i;    // Boxing
int j = (int)o;  // Unboxing


Assign value of value type toobject When an object is referenced, a "box" is assigned to save this value. This bin is an instance of the reference type, and this value is copied to the bin. Instead, when the object reference is explicitly converted to a value type, the referencedobject Whether it is a box with the correct value type. If the check succeeds, the value in the box is copied to the value type.

The unified type system of C# actually means treating value types "on demand" asobject Quote. Given this uniformity, a general purpose library using type object can be derived fromobject All types of use are combined, including reference type and value type.

C# has a variety of variables, including fields, array elements, local variables, and parameters. Variables indicate storage location. Each variable has a type that determines which values ​​can be stored in the variable,

As described below:

Can't do itnull The value type

  • Values ​​with exact type

A value type that can be null

  • null value or value with exact type

object

  • null reference, reference to objects of any reference type, or reference to boxed values ​​of any value type

Class Type

  • null reference, reference to class type instance, or reference to class instance derived from class type

Interface type

  • null reference, a reference to an instance of a class type that implements an interface type, or a reference to a boxed value that implements an interface type value type

Array type

  • null reference, reference to array type instances, or reference to compatible array type instances

Delegate Type

  • null reference or reference to compatible delegate type instances

IV. Program structure

Key organizational structure concepts in C# include programs, namespaces, types, members, and assembly*. The program declares a type, and the type contains members and is sorted into the namespace. Type examples include classes, structures, and interfaces. Member examples include fields, methods, properties, and events. The compiled C# program is actually packaged into the assembly. The file extension of an assembly is usually .exe or .dll, depending on whether it implements the application or library.

As a small example, consider an assembly containing the following code:

namespace ;

public class Stack<T>
{
    Entry _top;

    public void Push(T data)
    {
        _top = new Entry(_top, data);
    }

    public T Pop()
    {
        if (_top == null)
        {
            throw new InvalidOperationException();
        }
        T result = _top.Data;
        _top = _top.Next;

        return result;
    }

    class Entry
    {
        public Entry Next { get; set; }
        public T Data { get; set; }

        public Entry(Entry next, T data)
        {
            Next = next;
            Data = data;
        }
    }
}

The fully qualified name of this class is

 This class contains multiple members:A _top field, two methods (Push and Pop), and an Entry nested class.Entry Class alsoContains three members:A property named Next, a property named Data, and a constructor.Stack It is a generic class. It has a type parameter T, which is replaced with a concrete type when used.

The stack is a "first-in-and-out" (FILO) collection. New element added to the top of the stack. When an element is deleted, the element is deleted from the top of the stack. The previous example declares the Stack type that defines the storage and behavior of the stack. You can declare a variable that references an instance of type Stack to use this feature.

An assembly contains executable code in the form of intermediate language (IL) instructions and symbolic information in the form of metadata. Before execution, the .NET common language runtime real-time (JIT) compiler converts IL code from the assembly into processor-specific code.

Since the assembly is a self-described functional unit containing code and metadata, there is no need to use the #include directive and header files in C#. You can use the common types and members contained in this assembly in a C# program by simply referring to a specific assembly when compiling the program.

For example, this program uses the assembly class:

class Example
{
    public static void Main()
    {
        var s = new <int>();
        (1); // stack contains 1
        (10); // stack contains 1, 10
        (100); // stack contains 1, 10, 100
        (()); // stack contains 1, 10
        (()); // stack contains 1
        (()); // stack is empty
    }
}


To compile this program, you need to reference the assembly containing the stack class defined in the previous example.

C# programs can be stored in multiple source files. When compiling a C# program, all source files are processed simultaneously and the source files are freely referenced to each other. Conceptually, it's like all source files are connected to a large file before they are processed. Forward declarations are never required in C# because the order of declarations is irrelevant (except for rare exceptions). C# does not restrict the source file from declaring only one public type, nor does it require that the file name of the source file must match the type declared therein.

This is the article about the introduction to the basic introduction of C# language. For more related C# language introduction, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!