Sunday, September 2, 2018

C# why need struct if class can cover it?




Just wondering why we need struct if class can do all struct can and more? put value types in class has no side effect, I think.



EDIT: cannot see any strong reasons to use struct



A struct is similar to a class, with the following key differences:




  • A struct is a value type, whereas a
    class is a reference type.


  • A struct does not support inheritance
    (other than implicitly deriving from
    object).

  • A struct can have all the members a
    class can, except the following:

  • A parameterless constructor

  • A finalizer

  • Virtual members




A struct is used instead of a class when value type semantics are desirable. Good examples of structs are numeric types, where it is more natural for assignment to copy a value rather than a reference. Because a struct is a value type, each instance does not require instantiation of an object on the heap. This can be important when creating many instances of a type.


Answer



Custom value types aren't absolutely necessary - Java does without them, for example. However, they can still be useful.



For example, in Noda Time we're using them pretty extensively, as an efficient way of representing things like instants without the overhead of an object being involved.



I wouldn't say that "class can do all struct can and more" - they behave differently, and should be thought of differently.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...