Basic part of C# language

Basic part of C# language

reference material:

  • b station video tutorial
  • Rookie tutorial
  • Only extract and record the review content that is useful for yourself

Write code: code. cs - generate - exe - execute

  • Console.Write(); Output does not wrap

  • Console.WriteLine(); Output and wrap

  • Console.ReadLine(); Read all characters entered by the keyboard and return a string. Press enter to exit

  • Console.Read(); Read the first character entered by the keyboard and return its corresponding ASCII value. Press enter to exit

  • Console.ReadKey(); Wait for the user to press any key and exit. (this function is used to stay in the console window until the user hits the keyboard. Otherwise, the sentence "Hello World!" will flash in the console window and cannot be viewed.)

1.C# program structure

using System;
//The first line of the program is using System- The using keyword is used to include the System namespace in a program. A program usually has multiple using statements.
namespace HelloWorldApplication
{
//The next line is the namespace declaration. A namespace contains a series of classes. The HelloWorldApplication namespace contains the class HelloWorld.
   class HelloWorld
//The next line is the class declaration. The HelloWorld class contains the data and method declarations used by the program. Classes typically contain multiple methods. Method defines the behavior of the class. Here, the HelloWorld class has only one Main method.
   {
      static void Main(string[] args)
      {
         /* My first C# program*/
         Console.WriteLine("Hello World");
//The Main method passes the statement Console.WriteLine("Hello World"); Specifies its behavior.
WriteLine Is a definition in System In namespace Console Class. This statement displays a message on the screen "Hello World". 
         Console.ReadKey();
//The last line is Console.ReadKey(); Is for VS.NET users. This causes the program to wait for the action of a key to prevent the screen from running quickly and closing when the program starts from visual studio. Net.
      }
   }
}
  • A namespace is directly understood as the address of a class

  • Its function is to logically divide classes to avoid duplicate names

2.C# basic grammar

In C#, variables are divided into the following types:

  • Value types
  • Reference types
  • Pointer types

The built-in reference types are object, dynamic and string.

Object type

  • Object is an alias for the System.Object class. Therefore, the object type can be assigned values of any other type (value type, reference type, predefined type or user-defined type).

  • However, type conversion is required before assigning values.

  • When a value type is converted to an object type, it is called boxing; On the other hand, when an object type is converted to a value type, it is called unpacking.

int val = 8;
object obj = val;//Converting integer data to object type (boxing)
int val = 8;
object obj = val;//Packing first
int nval = (int)obj;//Re unpacking

Dynamic type

You can store any type of value in a dynamic data type variable. Type checking of these variables occurs at run time.

Syntax for declaring dynamic types:

dynamic d = 20;

String type

  • Allows you to assign any string value to a variable.

  • The string type is an alias for the System.String class.

  • It is derived from the Object type.

  • Values of type String can be assigned in two forms: quotation marks and @ quotation marks.

string str = @"C:\Windows";
string str = "C:\\Windows";

Pointer type

Shape as c/c++

3. Type conversion

  *// Cast double to int*
  i = (**int**)d;

such as:

ToString
Converts a type to a string type.

  Console.WriteLine(i.ToString());

For details, please refer to the rookie tutorial: C # type conversion | rookie tutorial (runoob.com)

Parse conversion: convert String to other data types

The data to be transferred must be like the data type

string strNumber="18.0";
int num02 = int.Parse(strNumber);//18

Convert any type to string

int number=18;
string str=number.ToString();

Implicit and explicit conversions

Small to large can be implicitly converted

Rules should be followed from large to small:

int a=100;
byte b=(byte)a;

int to short cannot be implicitly converted

4.C# constant

Such as c++/c

Note 1: the naming rules start with lowercase letters. If multiple words are included, the first letters of other words are capitalized except the first word. The prefix type is added for ease of understanding

Note 2: static and dynamic constants

1. Static constant (compile time constant) const

The value is determined at compile time. It must be initialized at declaration time and cannot be changed later. It can be defined in classes and methods. The definition method is as follows:

const double a=3.14;// Method for correctly declaring constants
const int b;         // Error, not initialized

2. Dynamic constant (runtime constant) readonly

Values are determined at run time, can only be initialized in declarations or constructors, and can only be defined in classes. The definition method is as follows:

class Program
{
    readonly int a=1;  // Initialize on declaration
    readonly int b;    // Initialization in constructor
    Program()
    {
        b=2;
    }
    static void Main()
    {
    }
}

decimal avoids double and float errors

decimal num01 = 3.0m;

A "+" sign is used for the connection between a string and a character

5.C# operator, judgment, loop

All shaped like C/C++

6.C# packaging

encapsulation

It is defined as "enclosing one or more items in a physical or logical package". In object-oriented programming methodology, encapsulation is to prevent access to implementation details.

An access modifier defines the scope and visibility of a class member. C # supports the following access modifiers:

  • public: all objects can be accessed;
  • private: the object itself can be accessed inside the object;
  • protected: only this class object and its subclass objects can be accessed
  • internal: objects of the same assembly can be accessed;
  • protected internal: access is limited to the current assembly or types derived from the containing class.

C # method | rookie tutorial (runoob.com)

7.C# access

  • such as
string.Format("The name of the gun is{0},Capacity{1}",gun,5)

{0} represents the first and {1} represents the second

  • Standard numeric string formatting
Console.WriteLine("amount of money:{0:c}",10);//Currency 10
Console.WriteLine("{0:d2}",5);//05, less than two digits are filled with 0
Console.WriteLine("{0:f1}",1.26);//1.3, precision rounding
Console.WriteLine("{0:p0}",0.1);//10% in percentage
Console.WriteLine("I love\"unity\"");Escape character
char c1='\'';//'
char c2='\0';//Null character
Console.WriteLine("Hello,\r\n I'm Lao Wang next door");
//Represents carriage return line feed
//\t stands for space 

8.C# nullable type

  • Double question mark
num3 = num1 ?? 5.34;      // num1 returns 5.34 if NULL
Console.WriteLine("num3 Value of: {0}", num3);
num3 = num2 ?? 5.34;
Console.WriteLine("num3 Value of: {0}", num3);

The function of the two question marks in C # is to judge?? Is the object on the left null? If not, use?? If the object on the left is null, use?? The object on the right.

  • Single question mark

? The single question mark is used to assign null to data types that cannot be directly assigned null, such as int, double, bool, etc., which means that this data type is Nullable.

int? i = 3;
//Equivalent to
Nullable<int> i = new Nullable<int>(3);
/*---------*/
int i; //Default 0
int? ii; //The default value is null
 //??  Double question marks are used to determine that a variable returns a specified value when it is null.   

Specific website: C # nullable types | rookie tutorial (runoob.com)

9.C# array

Arrays are beginning to differ in c# and c/c + +

datatype[] arrayName;

Among them,

  • datatype is used to specify the type of elements stored in the array.
  • [] specifies the rank (dimension) of the array. Rank specifies the size of the array.
  • arrayName specifies the name of the array.
double[] balance;//Declaration array
  • Declaring an array does not initialize the array in memory. When initializing an array variable, you can assign a value to the array.

  • Array is a reference type, so you need to use the new keyword to create an instance of the array.

double[] balance = new double[10];

Assign to array

//The first way
double[] balance = new double[10];
balance[0] = 4500.0;
//The second way is to declare and assign values
double[] balance = { 2340.0, 4523.69, 3421.0};
//Create and initialize
int [] marks = new int[5]  { 99,  98, 92, 97, 95};
//Ignore size initialization
int [] marks = new int[]  { 99,  98, 92, 97, 95};
//Assign an array variable to another target array variable
//The destination and source point to the same memory space
int [] marks = new int[]  { 99,  98, 92, 97, 95};
int[] score = marks;

Access array

using System;
namespace ArrayApplication
{
   class MyArray
   {
      static void Main(string[] args)
      {
         int []  n = new int[10]; /* n Is an array with 10 integers */
         int i,j;


         /* Initializes the elements in array n */        
         for ( i = 0; i < 10; i++ )
         {
            n[ i ] = i + 100;
         }

         /* Output the value of each array element */
         for (j = 0; j < 10; j++ )
         {
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
         Console.ReadKey();
      }
   }
}

Output results:

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

You can also use foreach to access the array. I feel very good

With Array, it has more convenient access usage

 foreach(int j in n )
 {
  int i = j-100;
  Console.WriteLine("Element[{0}] = {1}", i, j);
 }
 Console.ReadKey();

On the use of arrays and their Array classes

C # Array | rookie tutorial (runoob.com)

Common operations:

  • Array.Reverse(list);---- reverse
  • Array.Sort(list);---- Sorting, only one-dimensional arrays are supported

10. Specific usage of c# String

C # String | rookie tutorial (runoob.com)

For example, connect, compare....

11.C# structure

C # String | rookie tutorial (runoob.com)

12.C# enumeration

enum <enum_name>
{ 
    enumeration list 
};
  • enum_name specifies the type name of the enumeration.
  • enumeration list is a comma separated list of identifiers.

example:

using System;

public class EnumTest
{
    enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };

    static void Main()
    {
        int x = (int)Day.Sun;
        int y = (int)Day.Fri;
        Console.WriteLine("Sun = {0}", x);
        Console.WriteLine("Fri = {0}", y);
    }
}
Sun = 0
Fri = 5

13.C# type

C # Class | rookie tutorial (runoob.com)

14.C# succession

Inheritance is an important concept in object-oriented programming. When creating a class, programmers do not need to completely rewrite new data members and member functions. They only need to design a new class and inherit the members of the existing class. The existing class is called the base class, and the new class is called the derived class.

  • grammar

    <Access modifier> class <Base class>
    {
     ...
    }
    class <Derived class> : <Base class>
    {
     ...
    }
    
  • What to pay attention to in inheritance: there can be multiple subclasses and only one parent class. However, although multiple parent classes cannot be inherited, the same purpose can be achieved through the interface.

  • Typical inheritance example -- from rookie tutorial

using System;
namespace RectangleApplication
{
   class Rectangle
   {
      // Member variable
      protected double length;
      protected double width;
      public Rectangle(double l, double w)
      {
         length = l;
         width = w;
      }
      public double GetArea()
      {
         return length * width;
      }
      public void Display()
      {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("the measure of area: {0}", GetArea());
      }
   }//end class Rectangle  
   class Tabletop : Rectangle
   {
      private double cost;
      public Tabletop(double l, double w) : base(l, w)
      { }
      public double GetCost()
      {
         double cost;
         cost = GetArea() * 70;
         return cost;
      }
      public void Display()
      {
         base.Display();
         Console.WriteLine("Cost: {0}", GetCost());
      }
   }
   class ExecuteRectangle
   {
      static void Main(string[] args)
      {
         Tabletop t = new Tabletop(4.5, 7.5);
         t.Display();
         Console.ReadLine();
      }
   }
}

15.C# polymorphism

16.C # interface * * (Interface)**

  • An interface defines properties, methods, and events, which are members of the interface.
  • The interface only contains the declaration of members. The interface provides the standard structure that derived classes should follow. The interface makes the classes or structures that implement the interface consistent in form.
  • Abstract classes are similar to interfaces to some extent, but most of them are only used when only a few methods are declared by the base class and implemented by the derived class.
  • The interface itself does not implement any function.
  • Abstract classes cannot be instantiated directly, but concrete classes with practical functions can be derived.

Define an instance of an interface declaration:

interface IMyInterface
{
    void MethodToImplement();
}
  • The interface declaration is similar to the class declaration. The interface declaration is punlic by default
  • Generally, the interface command starts with the letter I. this interface has only one method MethodToImplement(), without parameters and return values. Of course, we can set parameters and return values as required.
  • After inheriting the interface, we need to implement the method MethodToImplement() of the interface. The method name must be consistent with the method name defined by the interface.
  • Interface calls can be superimposed. For example, if an interface undertakes another interface and is undertaken by a class, this class can call the methods in the two interfaces
  • For specific practical examples, see: C # Interface | rookie tutorial (runoob.com)

17.C# Namespace

  • Namespaces are designed to provide a way to separate a set of names from others.
  • The name of a class declared in one namespace does not conflict with the name of the same class declared in another namespace.
namespace namespace_name
{
   // Code declaration
}
  • using keyword can use functions and methods in the namespace, so you don't need to add the name of the namespace in front

for example

using System
//Then calling the method in the system space can no longer write out the system
    console.WriteLine("Hello world")
  • Namespaces can also be nested
  • You can use the dot (.) operator to access members of nested namespaces

18.C# preprocessor instructions

  • The preprocessing instruction instructs the compiler to preprocess the information before the actual compilation starts
  • All preprocessor instructions begin with # and on a line, only white space characters can appear before preprocessing instructions. Preprocessing instructions are not statements, so they do not end with.
  • The C# compiler does not have a separate preprocessor
  • Preprocessor instructions work during conditional compilation. Unlike C/C + +, they are not used to create macros. A preprocessor instruction must be the only instruction on the line.

Common preprocessors:

#define pi
    //Define a pi
#if(pi)
    //Check whether the condition is true

For more details, see:

C # preprocessor instructions | rookie tutorial (runoob.com)

Character escape, character class, anchor point, grouping construction, qualifier, back reference construction, backup construction, replacement, miscellaneous construction and Regex class in C #

C # regular expressions | rookie tutorial (runoob.com)

19.C# exception handling

C# exception handling is based on four Keywords: try, catch, finally and throw.

  • Try: a try block identifies the code block of a specific exception to be activated, followed by one or more catch blocks.
  • Catch: the program catches exceptions through the exception handler. The catch keyword indicates the capture of exceptions.
  • Finally: the finally block is used to execute a given statement regardless of whether an exception is thrown. For example, if you open a file, the file will be closed regardless of whether an exception occurs.
  • Throw: when a problem occurs, the program throws an exception. Use the throw keyword to complete.

Syntax:

try
{
    //Exception statement
}
catch(ExceptionName e1)
{
    //Error handling code
}
finally
{
    //Statement to execute
}    

C # exception handling | rookie tutorial (runoob.com)

20. Input and output of c# documents

C # file input and output | rookie tutorial (runoob.com)

21. var keyword in C #

  • VAR is a new type of variable defined in 3.5, which actually weakens the definition of type. VAR can replace any type

  • The compiler will judge what type you want to use according to the context,

  • var can be understood as anonymous type. We can think of it as a placeholder for declaring variables.

  • It is mainly used when the data type cannot be determined when declaring variables.

There are four characteristics when using var to define variables:

  1. It must be initialized at definition time. That is, it must be in the form of var s = "abcd", not in the following form: var s; s = "abcd";

  2. Once the initialization is completed, you can no longer assign a variable a value different from the initialization value type.

  3. var is required to be a local variable.

  4. Using var to define variables is different from object. It is exactly the same in efficiency as using strongly typed variables.

Keywords: C#

Added by bryanzera on Mon, 20 Sep 2021 17:55:46 +0300