Introduction to Structs in C#

By Jon Roberts

This article is design to give a basic introduction to Structs and the use for them in C# code.

Structs are similar to Classes in that both represent data structures that can have data members and functions. Unlike Classes, Structs are value types and do not require heap allocation.

Difference between Classes and Structs

 



Structs are useful for small data structures that have values with semantics. Examples are storing points in a coordinates system, or value-pair in a dictionary.

Data Types Supported

All basic variable types are supported when declaring a struct. Also the Database types are support allowing for extended value support and a more direct value translation to values found in application databases. Below in listed the Database types that are supported.

DBInt
allows support of all standard integer type values and also a null value to represent unknown.
DBBool
support for standard true false stats of boolean type also support a third state for null
 

 

Basic declaration example

struct Cord {
public int xcord, ycord, zcord;
public Cord(int xcord, int ycord, int zcord){
this.xcord = xcord;
this.ycord = ycord;
this.zcord = zcord;
}
}

Struct used in code

Cord mycord = new Cord(123,30,255);
Cord mycord2 = mycord;
mycord.xcord = 100;
System.Console.WriteLine(mycord2.xcord)

Usage of this in Structs

Within the declaration of the Struct the this is used to reference of the instance of the struct. The usage of the this keyword is constrained to the struct and will not access items outside the scope of the struct during declaration.

The this keyword will function normally when used in the code outside of the struct declaration.

Summary

Structs can be usefule when working with small datasets allowing for the developer to reduce the need to interact with the database until the completion of data manipulation and a final write to the database is needed.

Closing

It should also be noted that Structs and be used in more advanced functionalities to include, index, overload of operators,and Interfaces. In the near future I will bring youn article covering this and other uses of Structs.

 

Until next time keep coding and try new techniques in your code.

Jon "Spectur" Roberts


Sections