Using an unassigned local variable: value type vs custom struct

The primitive value type of C #, for example int, is a structure. So why intnot initialized? I think this should be the default constructor. On the other hand, the user structure is fine.

In the following code

struct STRCT { }
class Program
{
    static void Main(string[] args)
    {
        STRCT strct;
        strct.Equals(8);
        strct.GetHashCode();
        strct.GetType();
        strct.ToString();

        int i;
        i.Equals(8);
        i.GetHashCode();
        i.GetType();
        i.ToString();
    }
}

while the first 5 lines of code are in order from the C # compiler view, the following 5 lines of code generate a compilation error:

use of an unassigned local variable

Please explain why? From my point of view, both types are structures and should have the same behavior.

+4
source share
4 answers

. :

struct-type , .

(STRCT strct) , , .

+8

, int STRCT , , , "".

:

struct STRCT
{
    public int X;
}

:

CS0165 'strct' ConsoleApplication1 D:\Test\CS6\ConsoleApplication1\Program.cs 15

# " " 5.3:

, (ยง5.3.3) ,

:

struct-type , .

, , ( ), " ", .

+4

Member, - , int , .

, .

, .

struct STRCT
{
    private int a;
}

.

+1

Structs value types

Unlike reference types, a value typecannot contain a null value. However, the NULL type function allows you to assign values โ€‹โ€‹to null types. Each value type has an implicit default constructor that initializes the default value of this type. Default Value Information

See - https://msdn.microsoft.com/en-us/library/s1ax56ch.aspx

0
source

Source: https://habr.com/ru/post/1667530/


All Articles