When you can use a structure, not a class

In a recent project I worked on, I created a structure in my class to solve the problem that I encountered when a colleague looked over my shoulder, he mockingly looked at the structure and said: "Move it to the class."

I had no arguments not to move it to a class other than I only , in this class, but this view falls because I cannot make it a nested class?

When can a structure be used?

+3
source share
5 answers

You should check the rules for using value types: http://msdn.microsoft.com/en-us/library/y23b5415(vs.71).aspx

The article lists several important points, but the ones that, in my opinion, are the most valuable, are as follows

  • Is the value immutable?
  • Do you want the type to have semantics of values?

If the answer to both questions is yes, then you almost certainly want to use a structure. Otherwise, I would advise going with the class.

There are problems using structures with a large number of members. But I believe that if I look at these two points above, I rarely have more than the recommended number of members / size in my value types.

+14
source

MSDN , . :

  • .
  • 16 .
  • .
  • .

.

+8

Class , Structure ( ).

, " ", , ; :

Public Class Foo
    Public Sub Bar
        Dim baz = New With { .Str = "String", .I = 314 }
    End Sub
End Class

( - , ), baz Sub . , Object , .

+2

, , , . , , . ( ByRef, ) .NET ICloneSomething.

.

, , , , 99% , , .

, , " strcuture" " ?". , " , , ?"

0

, , , , . , .

  • .
  • You want to be able to make the equivalent of reinterpret_cast with relative security (provided that the structure does not contain fields that are themselves reference types.

Usually these are extreme cases and (with the exception of interop) are not recommended if their use is not necessary for the success of the project / program.

0
source

Source: https://habr.com/ru/post/1706243/


All Articles