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

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

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

19条回答
  •  灰色年华
    2020-11-22 02:00

    A short summary of each:

    Classes Only:

    • Can support inheritance
    • Are reference (pointer) types
    • The reference can be null
    • Have memory overhead per new instance

    Structs Only:

    • Cannot support inheritance
    • Are value types
    • Are passed by value (like integers)
    • Cannot have a null reference (unless Nullable is used)
    • Do not have a memory overhead per new instance - unless 'boxed'

    Both Classes and Structs:

    • Are compound data types typically used to contain a few variables that have some logical relationship
    • Can contain methods and events
    • Can support interfaces

提交回复
热议问题