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

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

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

19条回答
  •  悲&欢浪女
    2020-11-22 02:12

    Difference between Structs and Classes:

    • Structs are value type whereas Classes are reference type.
    • Structs are stored on the stack whereas Classes are stored on the heap.
    • Value types hold their value in memory where they are declared, but reference type holds a reference to an object memory.
    • Value types destroyed immediately after the scope is lost whereas reference type only the variable destroy after the scope is lost. The object is later destroyed by the garbage collector.
    • When you copy struct into another struct, a new copy of that struct gets created modified of one struct won't affect the value of the other struct.
    • When you copy a class into another class, it only copies the reference variable.
    • Both the reference variable point to the same object on the heap. Change to one variable will affect the other reference variable.
    • Structs can not have destructors, but classes can have destructors.
    • Structs can not have explicit parameterless constructors whereas classes can. Structs don't support inheritance, but classes do. Both support inheritance from an interface.
    • Structs are sealed type.

提交回复
热议问题