C # basics

Tram Ho

1. Memory Management (Memory Management)

To go into memory management, you should understand what happens inside a .Net application when you declare a variable. When you declare a variable, that variable will be allocated some parts (called chunk) of memory (memory) in ram, this memory has 3 things inside: data type, value, variable name.

The picture above explains what happens in memory when declaring the variable and most importantly the data type of the variable so that the variable’s memory will be allocated on the stack or heap.

  • Stack:
    • It is a LIFO (Last-in-first-out) structure, meaning that any variable that comes in later must come first (ie use the variable that comes in later, and then release it (any variable that cannot be used will be thrown away. ) then we can use the variables that were added earlier on the stack, these variables I am saying are they belong to the same method).
    • Variables that are allocated memory on the stack store their value directly in memory and access to this variable is very fast, it is allocated memory when the program compiles.
  • Heap: Variables are memory allocated in a random order and you can access it any time you want, then it will be released by garbage collector when you are not using it anymore, they memory is allocated on the heap at runtime and access to these variables takes longer than the variables on the stack.
  • Refer to the detailed example here , here , here and here!

2. Class

  • Class can only inherit from one other class or inherit one or more interfaces.
  • Class is declared directly inside a namespace and has the reach level of public or internal, the default is internal.
  • Class members, including nested classes, will have one of the six levels outlined below, by default for class members to be private.
  • Generic Classes are used to encapsulate operations, fields, and properties that belong to any data type (ie they are not exclusive to any data type). Commonly used for collections such as: lists, hash tables, stacks, queues, trees … read more here and here!
  • A class can contain the following declarations:
    1. Constructors, Finalizers (Also known as Destructors): Shown below.
    2. Constants: Is an immutable value (can not be changed) and only integrated types (ie types available in C # except object type) are declared constants and must be initialized when declared.
    3. Fields (field):
      • A variable of any data type and is declared directly inside the class or struct. For example: private DateTime date;
      • These fields are usually private or protected, and their data can be accessed via properties or methods or Indexers. If private field data is accessed by a public property, that field is called a backing store or backing field.
    4. Methods
    5. Properties:
      • Used to read, write or calculate the value of private fields so properties are also called accessor, in accessor get {} is used to read data, set {} is used to set values ​​and get {}, set { } also known as “property accessor”, we sometimes call each one as an accessor.
      • Auto-Implemented Properties: It is an attribute that we do not have any processing (ie no code) in get {} and set {}, making its property declaration short more compact, available from C # 3.0 and higher. This attribute requires accessor get {}. For example: public string Name {get; set; }
      • If the auto-deployment property is declared as in the above example, the compiler will create an anonymous and private backing field, which is only accessible via accessor get {}, set {}. In C # 6.0, this property can be assigned a value when declared. For example: public string Name {get; set; } = “cuong”;
    6. Indexer: Allows the object of the class or struct to be indexed like an array (In a sense, the object is like an array), the indexer is almost identical to a property except the Indexer it has parameters and uses parameters. refer to this instead of Indexer’s name.
    7. Operators: For example: +, -, *, / ….
    8. Events: An event that allows a class or object to notify another class or object about an action that the class or other object of interest has occurred to perform processing tasks. there. The class that sends (or raises) the event is called the publisher and the class that receives (or handles) the event is called the subscriber. Events are commonly used in window forms or in web applications, read more here!
    9. Classes: In C # you are allowed to define a class within another class, read more here!
    10. Interfaces: Dc is declared in the class and rarely declared in the class, most interfaces are declared outside the class.
    11. Delegates, Structure types, Enumeration types: Described below.
  • The program illustrates class in C #:

3. Naming rules

  • The following naming rules apply to almost every component named in C # such as: interface, class, method, field, properties, ….
    • The characters allowed are: [AZ], [az], [0-9]), _ (underscore)
    • Names can not start with numbers, can only begin with letters or underscores, and cannot contain spaces.
    • A keyword cannot be used as a name. If used, the “@” prefix must be added before the keyword. For example: @if
    • Names in C # are case sensitive and must not contain underscores.
    • The name has no more than 512 characters.

4. Accessibility Levels

  • Use Access Modifiers (public, protected, internal, or private) to specify the reach level for class members .
    public: Unlimited access.
    internal: Can be accessed from anywhere in an assembly.
    private: Access is restricted to the current class.
    private protected: Access is in the current class (the base class) and the derived class and must be in an assembly.
    protected: Access is restricted to the base class (parent class) and derived class (subclass).
    protected internal: Access is limited to one assembly (Basically it’s limited to a .cs file) and can be accessed within the derived class (derived class) in another assembly. (Read more about assemblies in .Net here , here and here ).
  • Reference here and here!

5. Data Types

5.1 – Value Types

  • Definition: Variables of this type directly store their data value in their own memory space and are mostly allocated (i.e. stored) on the stack (mostly because: If struct If created as a local variable in a function, it will be stored on the stack, in other cases the struct is still stored in the heap, read more here ). The derived class for this data type is: System.ValueType.
  • Illustration: We have a variable int i = 100 , the system will store 100 in the memory space allocated to variable i (This memory allocation is done by the CLR, read here and here ). The following image illustrates more clearly how 100 is stored at an assumed location in ram memory.
  • Value types are further divided into other types:
    • Simple type:
      • Signed integral: sbyte, short, int, long
      • Unsigned integral: byte, ushort, uint, ulong
      • Unicode characters: char
      • IEEE binary floating-point: float, double
      • High-precision decimal floating-point: decimal
      • Boolean: bool
    • Enum type or enumeration type: A type defined by a set of named constants (this name must not contain numbers) of integral numeric types ( integral numeric types ) only one integer and this number can be of many types such as: int, byte, long …), these constants have a default int value of 0, 1 … respectively (read more full details here , here and here! ):
      • User-defined type by template: enum Ten_Enum {…}
    • Structure type or Struct types:
      • Used to encapsulate data and related functions (it is almost identical to the class I will tell the difference between these two guys below), a structure can contain: constructors, constants, fields, methods, properties, indexers and events etc.
      • Syntax:
      • You can copy a structure object to another using the “=” assignment operator.
      • Nesting of Structures: Structure A nests structure B when you create object B in A’s body, then A’s objects will have both A and B’s data elements but access the That component of A is different from B (read more here! ).
    • Nullable Value Type:
      • In C #, you cannot assign a null value to a variable, but since C # version 2.0 and up, you can assign a null value to a variable called nullable type, this type works with simple type (Simple Type) of value type, C # version 8.0 and above also supports nullable for reference type.
      • Any variable of type is simply nullable, it is an instance of the structure, System.Nullable <T>.
      • Syntax:
      • The default value for nullable variables is null and you can assign the value of the non-nullable variable to the corresponding nullable variable (that is, both of these variables must be of the same simple type), for example:
  • Passing variables of type value type: When you pass this variable to a method (I call method B), the variable is duplicated, then that copy is passed to B and when you change the value. of the variable passed to B you are changing and working on the copy, not the original of the passed variable.

5.2 – Reference types

  • Definition: The Reference type does not directly store its value, it stores the address where the value is being stored (In a way: a reference type variable contains a pointer ( pointer) point to another memory location that is storing the data), variable values ​​of this reference type are stored in the heap.
  • Illustration: We have 1 variable: string s = “Hello World !!” The following screenshot shows how the system allocates memory for the variable above (the system chooses a random memory location in the ram for variable s, the value of this variable s is stored on the stack and it is a location. Only the memory where the value is stored and this value is stored on the heap, read more here! ).
  • The reference type is divided into:
    • Class Types:
      • object : The object type is an alias of System.Object so you can use System.Object instead of object and vice versa. In C #, all user-defined types, reference types, value types inherit directly or indirectly from System.Object, so you can assign any value (string, number …) to the object. Before assigning a value of a class type to another variable, it is necessary to convert the type. When a variable of type value is converted to an object, it is called boxing, and vice versa is unboxing.
      • Unicode character string (Class name is System.String): string
      • The type is defined by the user in the form: class tenClass {…}
    • Interface types:
      • The user-defined type follows the pattern: interface tenInterface {…}
    • Array Types:
      • Array one-dimensional or multidimensional: int [] and int [,] …
      • Used as the return type of the method or used to set the type of the variable, read more here and here! .
    • Deleate Types:
      • Delegate is an object that references a method or you can also say a delegate is a variable of reference type that holds a reference to any method that has the same signature (parameters and return type must be the same). delegate.
      • Declare a delegate type like you are defining a method signature , it has the return value and parameters.
      • Delegates are often used in event handlers or to execute callback functions (Callback is a function passed as an argument to another method, to create a callback in c # you need to store the function’s address in. a variable by using a delegate or using a lambda Func or Action).
      • Syntax:
      • Reference here , here and here!
    • Tuple style:
      • Tuple is a structured type containing many values ​​of different types and tuple does not allow method definition in tuple. (A variable of type tuple is like an object of a class with only fields). For example:
      • Tuple is also used in methods when you want to return multiple values ​​without using ref or out parameters (i.e. the return type for the method is tuple), used when you need to pass multiple values ​​to method passed a parameter.
      • You can use tuples instead of anonymous types in LINQ queries and in other cases.
      • The elements in the tuple can overlap and tuple limit 8 elements in it, if you want to have many elements, you must use nested tuple, easy to cause chaos so ae be careful.
      • Tuple is a reference type and is allocated memory on the heap so in a program that uses a lot of Tuple it will affect the CPU (ie increase CPU activity).
      • Reference here , here and here! .
  • Reference Type Variation: When you pass a variable of this type (called x) to a method (called B), this variable x is not duplicated to pass to B, but directly passes the address of x to B. So when in B you change the actual value of the parameter (this parameter takes the value directly from x), you are changing the actual value of x. For example:

    Explanation: When you pass the std1 object to the ChangeReferenceType method, in fact, you are passing the memory address of sdt1 to the method (that is passing to std2), so in that method you change on std2 ie is changing on std1 because both std1 and std2 point to std1’s memory address.
  • The default value for variables of reference type is null (that is, they don’t refer to any objects) when they are not initialized (ie, are not assigned a value). Value types cannot be null, except for value types that can be null.

6. Difference between Class and Struct

Class is a reference type that should be allocated memory on the heap (that is, the objects of the class are created on the heap) and are often used in large programs.Struct is a value type that should be allocated memory on the stack (ie struct objects are created on the stack memory) and usually used in small programs.
Contains Constructor, destrcutorContains no destructors and constructors without parameters, only constructors with parameters and static constructors are allowed.
Use the new keyword to create an objectCan create objects without the new keyword
Class can inherit from 1 class and 1 or more interfacesIt is not allowed to inherit struct or other class but it can inherit from 1 or more interfaces
Members of the class can be protectedIs not
Functions in class can be virtual or abstractIs not

7. Constructor and Destructor

7.1 – Constructor

  • Constructor (constructor): is a specialized function used to assign values ​​to fields, properties each time you create an object with the keyword new. This constructor has the same name as the class name of the constructor.
  • A few rules related to constructors:
    • A class without a constructor will have a default constructor created by the compiler (the default constructor is a no-parameter constructor) to assign default values ​​to fields, properties, specifically. , initialize values ​​for all numeric variables such as: int, double … are 0, strings and objects are assigned null.
    • The constructor with public access level allows us to create an object in the current or referenced assembly (if an object can be created in another .cs file in the project, if it is private or protected, it will error when creating the object. in another .cs file).
    • The constructor has one or more parameters.
    • A class can have multiple constructors, this constructor must have different parameters (the number of parameters or the type of parameter is different when two or more constructors have the same number of parameters).
    • The constructor returns no value (of type void).
    • Read more about constructors here!
  • Static Constructor:
    • Static constructors are often used to initialize static data, or perform a function that you only want to perform once. This static constructor is automatically called (executed) before the first instance (understood as an object) is created or the static members are referenced (i.e. that variable is used by you) and it is also executed. before the constructor is not static. For example:
    • A few notes regarding static constructors:
      • There is no access modifier and no parameters.
      • Class or struct has only one static constructor.
      • Not be inherited or overloaded.
      • Do not call it directly, it will be automatically called by the CLR.
      • With static fields (properties) that you do not provide static contructors to initialize values ​​for that static variable, those variables will be assigned default values ​​(Click here and here to see the default values ​​of each type. !).
      • The properties that you declare are: static readonly are only assigned values ​​in static constructor or at declaration time (ie initialization). And those properties should be initialized at the declaration instead of in the static constructor in order for the runtime to be more optimized.
    • Read more here and here!
  • Constructor in inheritance:
    • The derived class does not inherit the constructor of the base class because we cannot define exactly how the objects of the derived class are instantiated (assuming the constructor is inherited and that constructor does it. If the constructor is used to create an object that makes the derived class without redefining the constructor, the object created may fail, read more here! ), so inheriting constructor means that the class leads Export permission to call the base class constructor.
    • Both the base class and the derived class contain default constructors. You create a derived class object, both constructors in both classes are implemented and the constructor in the base class is executed first.
    • If both classes have a constructor with parameters but in the base class you do not specify a default constructor, the compiler will report an error ( This place I do not understand why it is error, you explain it for me! explanation here is also deadlock ). To fix that error, you use the keyword base.
    • Read more here!

7.2 – Destructor

  • The destructor is a function within the class that is used to delete the objects of the class when they are no longer used to recover space, disconnect the I / O file associated with the object. of the class to be deleted …
  • A few notes:
    • A class has only one destructor and this destructor is called by Garbage collector of the .Net Framework.
    • The destructor has no return type, parameter, modifier (or See what the modifier has in the left column here! ), Has the same name as the class name and prefix “~” in front to distinguish vs constructor.
    • The destructor is only used in classes, but in structs, it can’t be overloaded or inherited.
  • Read more here and here!

8. Function Overloading

  • Function overloading is a function used to override an existing function, function overloading must have the same name and return type as function overloaded, different singnature (different number of parameters or data type of another parameter. each) of functions overwritten with those that were previously overwritten.
  • Illustration:

9. Interfaces

  • Definition: You understand as simple as this, Mr. A, Mr. B, Mr. C … do business together, these guys all have a common contract that contains rules and regulations that every cell must implementation, an interface it as a contract contains the declarations of related functions that non-abstract classes or structs that adjacent Interfaces must implement those functions (ie, extend that functionality. in class or struct, see details in the section I illustrated below).
  • An interface can be a member of a namesapce or a class, declarations in the interface can contain the declarations of the following members: Methods, Properties, Indexers, Events.
  • Declarations in interfaces are usually no body, but with C # version 8.0 and above, a member can declare body, this is called “default implementation” and the interface it provides that default implementation for Class or struct does not provide an implementation for that member (ie, do not override that member).
  • Interface does not contain declarations (field) can contain static declarations of methods, fields, properties.
  • An interface has no members that are private, protected or internal because all members of the interface default to public and abstract.
  • Interface can inherit from 1 or more interfaces, 1 class inherits 1 or more interfaces, but can only inherit 1 class.
  • Illustration:
  • Reference here , here and here!

10. Reusability

When a class is created this class can be distributed to other programmers for use in their code, this is called reusability, or in .Net terminology reuse This is called a components or a DLL (ie to refer to a class that is reused).

11. Partial classes

  • A class is spread over many files (that is, dividing a class into parts, each part on a file and on each part there are properties and methods to perform a certain function different from the others on other files. there).
  • Advantages: short, clear (this function for which cell to write), easy to upgrade a function because it is clear. Cons: Multiple files, prone to duplicate property and method names, difficult to manage properties because it is in multiple files.

12. Suggestions

Thank you for reading my article, where there are mistakes in my article, misunderstanding or something, I hope you give me your comments so that I can improve the best way, thank you!

13. C # references.


Share the news now

Source : Viblo