C# Struct

Array Class Collections File Keyword String .NET ASP.NET Cast Compression Data Directive Enum Exception If Interface Lambda LINQ Loop Method Number Process Property Regex Sort StringBuilder Struct Switch Time Windows WPF

Struct

Objects live on the managed heap. Structs often reside on the evaluation stack. Every program uses simple structs. All value types (int, bool, char) are structs.
And custom structs,
often not advisable,
are also used.

Example

A struct uses syntax similar to a class. It is a type definition. To begin, we describe a struct called Simple: this struct stores three values, including an int, a bool and a double value.

Stack:Please notice how, in Main, the struct is created on the stack. No "new" keyword is used. It is used like a value type such as int.

Based on:

.NET 4.5

Program that declares struct: C#

using System;

class Program
{
    struct Simple
    {
	public int Position;
	public bool Exists;
	public double LastValue;
    };

    static void Main()
    {
	// ... Create struct on stack.
	Simple s;
	s.Position = 1;
	s.Exists = false;
	s.LastValue = 5.5;

	// ... Write struct field.
	Console.WriteLine(s.Position);
    }
}

Output

1

Debugger

Framework: NET

There are practical uses of structs. We just have not seen any yet. Next, we explore a struct within the Visual Studio debugger. The struct has the composite name "Program.Simple": it is nested within the Program class.

Tip:In the debugger, you can inspect variables like the struct in this program. Depending on your approach to coding, this may help.

Struct: Visual Studio debugger

Values

Value

Structs are custom value types that store the values in each field together. They do not store referenced data, such as the character array in a string. MSDN says that structs "do not require heap allocation."

Further:Variables "directly contain the data of the struct." And "a variable of a class type contains a reference to the data."

Structs Tutorial: MSDN

This means that with structs you avoid the overhead of objects in the C# language. You can combine multiple fields. This reduces memory pressure. And it improves performance if the stack is not overwhelmed.

Value semantics:This term indicates whether the variable is being used like numbers and values are, or as an inherited class.

Note:MSDN states that "complex numbers, points in a coordinate system, or key-value pairs in a dictionary" are included.

Usage

Steps

Struct types should be considered in performance-sensitive parts of a program. Points containing coordinates and positions are excellent examples of structs, as is the DateTime struct.

DateTime

In this program, we demonstrate that a DateTime is a struct. We create a DateTime and then copy it into a separate DateTime variable. When the original changes, though, the copy remains the same. The memory is kept separate.

Program that uses DateTime struct: C#

using System;

class Program
{
    static void Main()
    {
	// DateTime is a struct.
	DateTime date = new DateTime(2000, 1, 1);

	// When you assign a DateTime, a separate copy is created.
	DateTime dateCopy = date;

	// The two structs have the same values.
	Console.WriteLine(date);
	Console.WriteLine(dateCopy);

	// The copy is not affected when the original changes.
	date = DateTime.MinValue;
	Console.WriteLine(dateCopy);
    }
}

Output

1/1/2000 12:00:00 AM
1/1/2000 12:00:00 AM
1/1/2000 12:00:00 AM
Note

Often in programs we have small classes that serve as collections of related variables stored in memory. Here we require no inheritance or polymorphism. These types often make ideal structs.

Structs are useful for storing coordinates of offsets in your files. These usually contain integers. It is also worthwhile to use structs for graphics. When using graphics contexts, we use structs for points and coordinates.

Note:MSDN provides an example of a nullable integer used for databases. Use this if you don't want to use Nullable(T).

Database Integer Type: MSDN

Property

Property

Next we see an example of using properties with the struct type. Remember that your struct cannot inherit like classes or have complex constructors. But you can provide properties for it that simplify access to its data.

Properties
Program that uses property on struct: C#

using System;

class Program
{
    static void Main()
    {
	// Initialize to 0.
	S st = new S();
	st.X = 5;
	Console.WriteLine(st.X);
    }

    struct S
    {
	int _x;
	public int X
	{
	    get { return _x; }
	    set
	    {
		if (value < 10)
		{
		    _x = value;
		}
	    }
	}
    };
}

Output

5

Stack, heap

Garbage collection visualization

Local value types are allocated on the stack. This includes integers such as "int i" for loops. When you create an object from a class in a function, it is allocated on the heap. The stack is normally much faster.

Note:The details of stacks and heaps are out of the scope here, but are worthwhile studying.

Structs are a value type and therefore inherit System.ValueType. This means they are copied completely when you pass them as parameters to methods. Structs can therefore degrade performance when passed to methods.

Struct vs. Class

Class

Constructor: create new

You can't easily change classes that inherit or implement interfaces to structs. You cannot use a custom default constructor on structs, as when they are constructed, all fields are assigned to zero.

Tip:You don't have to instantiate your struct with the new keyword. It instead works like an int—you can directly access it.

Program that uses class: C#

class Program
{
    class C
    {
	public int X;
	public int Y;
    };

    static void Main()
    {
	C local = new C();
	local.X = 1;
	local.Y = 2;
    }
}

Program that uses struct: C#

class Program
{
    struct C
    {
	public int X;
	public int Y;
    };

    static void Main()
    {
	C local;
	local.X = 1;
	local.Y = 2;
    }
}

Null

Null keyword

You cannot compare a struct instance to the null literal.
If this is confusing,
think of structs as ints
or bools. You can't set your integer variable to null. Nullable types, however, are a generic type that can be null.

Nullable types. The C# language provides a nullable type wrapper for any object. With the nullable wrapper, you can assign the null literal to even values like integers. In some programs this simplifies syntax.

Note:Nullable types themselves (System.Nullable) are implemented with structs.

Nullable BoolNullable DateTimeNullable IntNullable Memory

Memory

We examine the memory usage of allocating many structs versus the memory usage of allocating many classes. I looked at the memory layout of the console program in the CLRProfiler.

CLRProfiler:This is a free tool by Microsoft that visualizes the memory allocations of .NET programs.

The first picture is the memory profile of the version that uses classes. It indicates that the List took 512 KB and was one object. Internally the List stored 100000 objects and required 3.8 MB.

ListsMemory usage of classes, not structs

Second image. Using structs, CLRProfiler indicates that the List took 24 bytes and contained one object of 4.0 MB. That one object is an array of 100000 structures, all stored together.

Memory usage of structs
Class version

Size of List:           1 object
			512 KB
Size of internal array: 100000 objects
			3.8 MB

Struct version

Size of List:           1 object
			24 bytes
Size of internal array: 1 object
			4.0 MB

This means that structs are not stored as separate objects in arrays, but are grouped together. This is possible because they are value types. We see that structs consume less memory.

Allocation speed

Performance optimization

Let's look at how quickly the .NET Framework can allocate lots of classes versus how fast it can allocate many structs. It was easier to gather speed benchmarks of structs. I compared two classes to two structs.

Note:Both pairs of opposites, class S and struct S, use either eight ints or four strings.

Classes tested in benchmark: C#

class S
{
    public int A;
    public int B;
    public int C;
    public int D;
    public int E;
    public int F;
    public int G;
    public int H;
}

class S
{
    public string A;
    public string B;
    public string C;
    public string D;
}

Structs tested in benchmark: C#

struct S
{
    public int A;
    public int B;
    public int C;
    public int D;
    public int E;
    public int F;
    public int G;
    public int H;
}

struct S
{
    public string A;
    public string B;
    public string C;
    public string D;
}

Strings are reference types. Their internal data is not embedded in the struct. Just the reference or pointer is. The performance benefits of structs with strings persists even when their referential data is accessed.

Struct/class allocation performance timing

Class with 8 ints:               2418 ms
Struct with 8 ints:               936 ms [faster]

Class with 4 string references:  2184 ms
Struct with 4 string references:  795 ms [faster]
Arrow indicates looping

Notes:10 million loops of 100000 iterations. Tests allocation speed of the data structures. Structs were much faster in both tests.

In this test, we see substantial speedups of over two times when allocating the structs. This is because they are value types allocated on the stack. Note they are stored in a List field.

Also:I tried to ensure accuracy of the test by assigning each field and avoiding property accesses.

Strings

String type

You can use string fields in struct types. Please note that the struct will not store the string's data. Strings are objects, so the data will be stored externally, where the reference points.

However:Using structs can improve performance with the string reference itself. References are also data.

ASP.NET

ASPNET web programming framework

In my ASP.NET project, I record thousands of referrer data objects. These store two string fields and a DateTime field. By hovering over DateTime in Visual Studio, you see that it too is a struct.

And:Because DateTime itself is a struct, it will be stored directly in the struct allocation on the stack.

Tip

Thus:In a struct with two strings and a DateTime, the struct will hold two references and one value together.

We replaced the class with a struct. This should improve performance by about two times and reduce memory. Some benefits depend on usage. If the type is often passed to methods, this optimization could reduce speed.

Program that uses struct in website: C#

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	var _d = new Dictionary<string, ReferrerInfo>();

	// New struct:
	ReferrerInfo i;
	i.OriginalString = "cat";
	i.Target = "mat";
	i.Time = DateTime.Now;

	_d.Add("info", i);
    }

    /// <summary>
    /// Contains information about referrers.
    /// </summary>
    struct ReferrerInfo
    {
	public string OriginalString; // Reference.
	public string Target;         // Reference.
	public DateTime Time;         // Value.
    };
}

Offsets

Int

In a database system I developed, file blobs are stored in large files together. I needed a way to store their offsets. Therefore I created a struct with two members. It had two ints storing positions.

Int

And:Structs were ideal here.
There were over 500 instances of the object.
And they only had two fields (both value types).

Program that uses Dictionary of structs: C#

using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// Stores Dictionary of structs.
	var _d = new Dictionary<string, FileData>();
	FileData f;
	f.Start = 1000;
	f.Length = 200;
	_d.Add("key", f);
    }

    /// <summary>
    /// Stores where each blob is stored.
    /// </summary>
    struct FileData
    {
	public int Start;
	public int Length;
    }
}

Pointers

Star, asterisk character

The C# language frees us from the nightmare that is C pointers. But understanding pointers is important. Pointers, like references, are values that contain the addresses of data. Pointers are blisteringly fast.

But:Their syntax and lack of error checking causes problems. They are harder to use than references.

Note:The struct keyword gives us more power over references and how fields are stored.

Pointers are used with structs in unsafe code.
Unsafe code is just that:
not safe,
but still usually functional. It is sometimes faster. The struct type can be used with fixed buffers as a memory region.

Fixed Buffers

ValueType

Net

In the .NET Framework, values such as integers are stored in structs. The ValueType class is an abstract base class for these values. You can refer to them with a ValueType reference.

ValueType Class

Structs are particularly useful for small data structures that have value semantics. Hejlsberg et al., p. 537

Summary

Important

Structs are an advanced topic. But every developer has used them in value types. By understanding value semantics, we learn an important performance optimization. Structs often degrade performance, so should be typically avoided.

C#