= Struct Definition = Structs are similar to classes but more limited in ways that make them suitable [[BR]] for representing lightweight value-container-only objects ( like a Point or Rectangle). Unlike classes (reference type) they are a value type and they cannot be inherited or inherit[[BR]] from another class or struct. Other differences from classes:[[BR]] * Within a struct declaration, fields cannot be initialized unless they are declared as const or static. * A struct may not declare a default constructor (a constructor without parameters) or a destructor. * Structs can only declare constructors that have parameters. * Structs are copied on assignment and when passed into methods. [[BR]] When a struct is assigned to a new variable or passed to a method, all the data is copied, and any modification to the [[BR]] new copy does not change the data for the original copy. However * A struct can implement interfaces. * A struct can be used as a nullable type and can be assigned a null value. Structures and their contained instance members are public by default though this may be[[BR]] overridden using the normal [wiki:AccessModifiers access modifiers] syntax. Idomatic usage suggests structs should not modify their accessmodifiers for visibility and[[BR]] should not declare any methods (If this is deemed necessary you should use a class instead).[[BR]] They should only be used as publicly accessible value containers. The syntax/grammar for declaring structures is similar to that of classes [[BR]] (barring the '''struct''' keyword and lack of the '''inherits''' clause) == Grammar == {{{ struct [is ] [has ] [where must be ] [implements [, ]...] [] [ [] [] [] [ [] [] [] [] [] ]... # empty (placeholder) structure struct [is ] [has ] [where must be ] [implements [, ]...] [] pass }}} == Platform == in .Net, all structs inherit directly from System.!ValueType, which inherits from System.Object. == Examples == {{{ # a simple Point-like struct struct CoOrds var x as int var y as int cue init(p1 as int, p2 as int) .x = p1 .y = p2 #// Declare and initialize struct objects. class TestCoOrds def main is shared # Initialize: coords1 = CoOrds() coords2 = CoOrds(10, 10) # Display results: print 'CoOrds 1: ' stop print 'x = [coords1.x], y = [coords1.y]' print 'CoOrds 2: ' stop print 'x = [coords2.x], y = [coords2.y]' assert coords1.x == 0 and coords1.y == 0 assert coords2.x == 10 and coords2.y == 10 /# Output: CoOrds 1: x = 0, y = 0 CoOrds 2: x = 10, y = 10 #/ }}} == Notes == == See Also == [http://msdn.microsoft.com/en-us/library/ah19swz4.aspx struct(C# Reference)] [http://msdn.microsoft.com/en-us/library/saxz13w4.aspx Structs(C# Programming Guide)] [http://msdn.microsoft.com/en-us/library/0taef578.aspx Using Structs( C# Programming Guide)] [wiki:LanguageTopics Back to LanguageTopics]