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 value types
- Assigning to a variable of struct types creates a copy of the value.
- All struct types are implicitly inherited from the System.Value type class.
- Boxing and Unboxing operations are used to convert between struct type and object type.
- A struct is not permitted to declare a parameterless instance constructor.
- A destructor declaration is not allowed for a struct.
- Default value of a struct is produced by setting all value type fields to the default value and all reference type values to null.
- Initializer value may not be set of a struct value when struct value is declared.
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