What's the difference between struct and class in .NET?

前端 未结 19 1383
一向
一向 2020-11-22 01:51

What\'s the difference between struct and class in .NET?

19条回答
  •  终归单人心
    2020-11-22 02:09

    In .NET the struct and class declarations differentiate between reference types and value types.

    When you pass round a reference type there is only one actually stored. All the code that accesses the instance is accessing the same one.

    When you pass round a value type each one is a copy. All the code is working on its own copy.

    This can be shown with an example:

    struct MyStruct 
    {
        string MyProperty { get; set; }
    }
    
    void ChangeMyStruct(MyStruct input) 
    { 
       input.MyProperty = "new value";
    }
    
    ...
    
    // Create value type
    MyStruct testStruct = new MyStruct { MyProperty = "initial value" }; 
    
    ChangeMyStruct(testStruct);
    
    // Value of testStruct.MyProperty is still "initial value"
    // - the method changed a new copy of the structure.
    

    For a class this would be different

    class MyClass 
    {
        string MyProperty { get; set; }
    }
    
    void ChangeMyClass(MyClass input) 
    { 
       input.MyProperty = "new value";
    }
    
    ...
    
    // Create reference type
    MyClass testClass = new MyClass { MyProperty = "initial value" };
    
    ChangeMyClass(testClass);
    
    // Value of testClass.MyProperty is now "new value" 
    // - the method changed the instance passed.
    

    Classes can be nothing - the reference can point to a null.

    Structs are the actual value - they can be empty but never null. For this reason structs always have a default constructor with no parameters - they need a 'starting value'.

提交回复
热议问题