Difference between revisions of "Struct"
esse quam videri
m (Text replacement - "<csharp>" to "<syntaxhighlight lang="csharp" line="1" >") |
|||
(5 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
− | == | + | [[Category:Object Oriented Programming]] |
− | + | [[Category:Programming Language Concepts]] | |
− | + | [[Category:C Sharp]] | |
+ | |||
+ | |||
+ | ==C# Struct== | ||
+ | C# structs are lightweight alternatives to classes. | ||
+ | Structs do not support inheritance or destructors, and are value typed objects similar to ints bool etc... while classes are reference types. | ||
+ | Structs are more memory efficient and and faster than classes. | ||
− | |||
Syntax | Syntax | ||
Line 9: | Line 14: | ||
[:interface-list {struct members} | [:interface-list {struct members} | ||
− | <syntaxhighlight lang="csharp | + | <syntaxhighlight lang="csharp">struct Dog |
{ | { | ||
public string name; | public string name; | ||
public string weight; | public string weight; | ||
public int age; | public int age; | ||
− | }</ | + | }</syntaxhighlight> |
− | |||
− | |||
− | A good example of a | + | A good example of a struct would be and something like a point. There may be many many points in a structure or graph and we would want the points to be a lightweight as possible. Since the point object won't have any methods this is a good time to use a struct. |
− | to be a lightweight as possible. Since the point object won't have | ||
− | <syntaxhighlight lang="csharp | + | <syntaxhighlight lang="csharp">struct Point |
{ | { | ||
public int x; | public int x; | ||
Line 41: | Line 43: | ||
return newPt; | return newPt; | ||
} | } | ||
− | }</ | + | }</syntaxhighlight> |
− | |||
− |
Latest revision as of 17:18, 10 June 2019
C# Struct
C# structs are lightweight alternatives to classes. Structs do not support inheritance or destructors, and are value typed objects similar to ints bool etc... while classes are reference types. Structs are more memory efficient and and faster than classes.
Syntax
[ attributes] [access-modifiers] struct identifier [:interface-list {struct members}
struct Dog
{
public string name;
public string weight;
public int age;
}
A good example of a struct would be and something like a point. There may be many many points in a structure or graph and we would want the points to be a lightweight as possible. Since the point object won't have any methods this is a good time to use a struct.
struct Point
{
public int x;
public int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public Point Add(Point pt)
{
Point newPt;
newPt.x = x + pt.x;
newPt.y = y + pt.y;
return newPt;
}
}