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

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

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

相关标签:
19条回答
  • 2020-11-22 02:04

    Besides the basic difference of access specifier, and few mentioned above I would like to add some of the major differences including few of the mentioned above with a code sample with output, which will give a more clear idea of the reference and value

    Structs:

    • Are value types and do not require heap allocation.
    • Memory allocation is different and is stored in stack
    • Useful for small data structures
    • Affect performance, when we pass value to method, we pass the entire data structure and all is passed to the stack.
    • Constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessary
    • The variables each have their own copy of the data, and it is not possible for operations on one to affect the other.
    • Do not support user-specified inheritance, and they implicitly inherit from type object

    Class:

    • Reference Type value
    • Stored in Heap
    • Store a reference to a dynamically allocated object
    • Constructors are invoked with the new operator, but that does not allocate memory on the heap
    • Multiple variables may have a reference to the same object
    • It is possible for operations on one variable to affect the object referenced by the other variable

    Code Sample

        static void Main(string[] args)
        {
            //Struct
            myStruct objStruct = new myStruct();
            objStruct.x = 10;
            Console.WriteLine("Initial value of Struct Object is: " + objStruct.x);
            Console.WriteLine();
            methodStruct(objStruct);
            Console.WriteLine();
            Console.WriteLine("After Method call value of Struct Object is: " + objStruct.x);
            Console.WriteLine();
    
            //Class
            myClass objClass = new myClass(10);
            Console.WriteLine("Initial value of Class Object is: " + objClass.x);
            Console.WriteLine();
            methodClass(objClass);
            Console.WriteLine();
            Console.WriteLine("After Method call value of Class Object is: " + objClass.x);
            Console.Read();
        }
        static void methodStruct(myStruct newStruct)
        {
            newStruct.x = 20;
            Console.WriteLine("Inside Struct Method");
            Console.WriteLine("Inside Method value of Struct Object is: " + newStruct.x);
        }
        static void methodClass(myClass newClass)
        {
            newClass.x = 20;
            Console.WriteLine("Inside Class Method");
            Console.WriteLine("Inside Method value of Class Object is: " + newClass.x);
        }
        public struct myStruct
        {
            public int x;
            public myStruct(int xCons)
            {
                this.x = xCons;
            }
        }
        public class myClass
        {
            public int x;
            public myClass(int xCons)
            {
                this.x = xCons;
            }
        }
    

    Output

    Initial value of Struct Object is: 10

    Inside Struct Method Inside Method value of Struct Object is: 20

    After Method call value of Struct Object is: 10

    Initial value of Class Object is: 10

    Inside Class Method Inside Method value of Class Object is: 20

    After Method call value of Class Object is: 20

    Here you can clearly see the difference between call by value and call by reference.

    0 讨论(0)
  • 2020-11-22 02:08

    Every variable or field of a primitive value type or structure type holds a unique instance of that type, including all its fields (public and private). By contrast, variables or fields of reference types may hold null, or may refer to an object, stored elsewhere, to which any number of other references may also exist. The fields of a struct will be stored in the same place as the variable or field of that structure type, which may be either on the stack or may be part of another heap object.

    Creating a variable or field of a primitive value type will create it with a default value; creating a variable or field of a structure type will create a new instance, creating all fields therein in the default manner. Creating a new instance of a reference type will start by creating all fields therein in the default manner, and then running optional additional code depending upon the type.

    Copying one variable or field of a primitive type to another will copy the value. Copying one variable or field of structure type to another will copy all the fields (public and private) of the former instance to the latter instance. Copying one variable or field of reference type to another will cause the latter to refer to the same instance as the former (if any).

    It's important to note that in some languages like C++, the semantic behavior of a type is independent of how it is stored, but that isn't true of .NET. If a type implements mutable value semantics, copying one variable of that type to another copies the properties of the first to another instance, referred to by the second, and using a member of the second to mutate it will cause that second instance to be changed, but not the first. If a type implements mutable reference semantics, copying one variable to another and using a member of the second to mutate the object will affect the object referred to by the first variable; types with immutable semantics do not allow mutation, so it doesn't matter semantically whether copying creates a new instance or creates another reference to the first.

    In .NET, it is possible for value types to implement any of the above semantics, provided that all of their fields can do likewise. A reference type, however, can only implement mutable reference semantics or immutable semantics; value types with fields of mutable reference types are limited to either implementing mutable reference semantics or weird hybrid semantics.

    0 讨论(0)
  • 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'.

    0 讨论(0)
  • 2020-11-22 02:09

    In addition to all differences described in the other answers:

    1. Structs cannot have an explicit parameterless constructor whereas a class can
    2. Structs cannot have destructors, whereas a class can
    3. Structs can't inherit from another struct or class whereas a class can inherit from another class. (Both structs and classes can implement from an interface.)

    If you are after a video explaining all the differences, you can check out Part 29 - C# Tutorial - Difference between classes and structs in C#.

    0 讨论(0)
  • 2020-11-22 02:09

    Structure vs Class

    A structure is a value type so it is stored on the stack, but a class is a reference type and is stored on the heap.

    A structure doesn't support inheritance, and polymorphism, but a class supports both.

    By default, all the struct members are public but class members are by default private in nature.

    As a structure is a value type, we can't assign null to a struct object, but it is not the case for a class.

    0 讨论(0)
  • 2020-11-22 02:09

    I ♥ visualizations, and here I've created a one to show the basic differences between structs and classes.


    For more information look below:

    • Classes and structs (official documentation).
    • Choosing Between Class and Struct (official documentation).
    0 讨论(0)
提交回复
热议问题