Difference between revisions of "Struct"

esse quam videri
Jump to: navigation, search
m (Text replacement - "</csharp>" to "</syntaxhighlight>")
m (Text replacement - "syntaxhighlight lang="csharp" line="1" " to "syntaxhighlight lang="csharp"")
Line 9: Line 9:
 
[:interface-list {struct members}  
 
[:interface-list {struct members}  
  
<syntaxhighlight lang="csharp" line="1" >struct Dog
+
<syntaxhighlight lang="csharp">struct Dog
 
{
 
{
 
  public string name;
 
  public string name;
Line 21: Line 21:
 
to be a lightweight as possible. Since the point object won't have an methods this is a good time to use a struct.
 
to be a lightweight as possible. Since the point object won't have an methods this is a good time to use a struct.
  
<syntaxhighlight lang="csharp" line="1" >struct Point
+
<syntaxhighlight lang="csharp">struct Point
 
{
 
{
 
     public int x;
 
     public int x;

Revision as of 03:23, 9 February 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}

struct Dog
{
 public string name;
 public string weight;
 public int age;
}

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.

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;
    }
}