Author - Dave Amour

Dave Amour has used computers for as long as he can remember and intially started out as an IT trainer delivering a range of IT courses but for the last 11 years has been focusing on the arena of web application development. He was worked for numerous companies over the years and is currently working for Audacs Software Ltd. Dave is also a keen squash player and an active and sucessful member of Experts Exchange

Please feel free to submit any constructive comments which you can do at the bottom of this page.

Dave may be available for programming tuition or consultancy work. Contact via dave@audacs.co.uk
Dave Amour - Click to view CV 

Structs in C#

A struct in C# is very simillar to a class but think of it as a lightweight version of a class.

Structs are value types and are stored on the stack rather than the heap so they use less resources.

Lots of built in types are actually structs so when considering whether your object should be a struct or a class then think about how these will be used and compare them with objects which Microsoft have made as structs rather than classes.  Note though a tendency to have structs for objects which hold and manipulate values rather than representing rich and functional objects.

Some examples of intrinsic types which are structs are as follows:

  • Int16
  • Int32
  • Int64
  • Byte
  • float
  • double
  • DateTime

You can confirm this by right clicking on one of these in Visual studio and clicking Go to definition when for lets say an Int32 you will see this:

So lets have a look at what a simple struct could look like.  We will create one to represent a point on a Graph consisting of an x and y co-ordinate.  We will alos create a little console app to use for testing our code. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace QuickTest
{
    class Program
    {
        static void Main(string[] args)
        {
            GraphPoint p = new GraphPoint();
 
            p.X = 10;
            p.Y = 20;
 
            Console.WriteLine("Graphpoint values are x={0} and y={1}", p.X, p.Y);
 
            Console.Read();
        }
    }
 
    public struct GraphPoint
    {
        private int x;
        private int y;
 
        public int X
       {
            get
            {
                return x;
            }
 
            set
            {
                x = value;
            }
        }
 
        public int Y
        {
            get
            {
                return y;
            }
 
            set
            {
                y = value;
            }
        }
    }
}
 


Ok so hopefully that was simple enough.

Note that we could have written this with fewer lines of code as follows but then we don't have the benefits of using properties just the same as when we are dealing with classes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace QuickTest
{
    class Program
    {
        static void Main(string[] args)
        {
            GraphPoint p = new GraphPoint();
 
            p.X = 10;
            p.Y = 20;
 
            Console.WriteLine("Graphpoint values are x={0} and y={1}", p.X, p.Y);
 
            Console.Read();
        }
    }
 
    public struct GraphPoint
    {
        public int X;
        public int Y;
    }
}


Taking the code above let's try adding a Constructor as follows:

    public struct GraphPoint
    {
        public int X;
        public int Y;
 
        public GraphPoint()
        {
 
        }
    }
 


If you do this and try and compile then you will get an error saying that Structs cannot contain explicit parameterless constructors.

The reason for this is that structs already have an implicit default constructor built in.  If we want to create a constructor then we have to put some code and parameters in it.  If we try and get away with just this:

    public struct GraphPoint
    {
        public int X;
        public int Y;
 
        public GraphPoint(int x, int y)
        {
 
        }
    }


then we again get a compilation error but this time stating that Field 'QuickTest.GraphPoint.Y' must be fully assigned before control is returned to the caller.

so we need to finish it off and go:

    public struct GraphPoint
    {
        public int X;
        public int Y;
 
        public GraphPoint(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    }


So we can therefore deduce that you must either not have a constructor(other than the implicit built in one) or if you do have a constructor then this must have parameters and all fields whether private or public must be initialised in the constructor.

Other differences in structs and classes is that structs cannot inherit from other classes but they can implement interfaces.

There are in fact many many more differences between structs and clases.  Rather than list them myself I shall point you in the direction of a very good listing and explanation of these:

www.jaggersoft.com/pubs/StructsVsClasses.htm 

Leave a comment

Name

Email (optional and not disclosed)



Email address is not disclosed but just used to alert you of new posts if entered
Word CV
HTML CV
PDF CV
Text CV
CMS Lite
ETraining
Planet Health
Florida Health
the Date Shack
Taylors
Emcat
Emtex
Browne Jacobson
Alliance & Leicester
Baird Leisure
Swarfega
Creature Comforts
Rugeley Chess Club
Katnip
Katmaid
Dudley NHS
Contact Me
Current Status