Difference between revisions of "Struct"

esse quam videri
Jump to: navigation, search
m (Text replacement - "<csharp>" to "<syntaxhighlight lang="csharp" line="1" >")
m (Text replacement - "</csharp>" to "</syntaxhighlight>")
Line 14: Line 14:
 
  public string weight;
 
  public string weight;
 
  public int age;
 
  public int age;
}</csharp>
+
}</syntaxhighlight>
  
 
This is a pretty lightweight dog and is pretty useless as a dog (It's can't even bark what fun is that) so I won't make an example.
 
This is a pretty lightweight dog and is pretty useless as a dog (It's can't even bark what fun is that) so I won't make an example.
Line 41: Line 41:
 
         return newPt;
 
         return newPt;
 
     }
 
     }
}</csharp>
+
}</syntaxhighlight>
  
 
[[Category:IAM Classes]][[Category:Object Oriented Programming]]
 
[[Category:IAM Classes]][[Category:Object Oriented Programming]]

Revision as of 18:29, 25 January 2016

Structs

- remember these
from week 2

Lightweight alternatives to classes. Structs do not support inheritance or destructors. Structs 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}

1 struct Dog
2 {
3  public string name;
4  public string weight;
5  public int age;
6 }

This is a pretty lightweight dog and is pretty useless as a dog (It's can't even bark what fun is that) so I won't make an example.

A good example of a stuct 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 an methods this is a good time to use a struct.

 1 struct Point
 2 {
 3     public int x;
 4     public int y;
 5 
 6     public Point(int x, int y)
 7     {
 8         this.x = x;
 9         this.y = y;
10     }
11 
12     public Point Add(Point pt)
13     {
14         Point newPt;
15 
16         newPt.x = x + pt.x;
17         newPt.y = y + pt.y;
18 
19         return newPt;
20     }
21 }