Structure type is a value type with data and related functionality encapsulated as a single unit.
- It is declared using the struct keyword.
- It is used for holding small data values, like number and bool values.
- It can be declared either public or internal (internal is the default access modifier).
- Its members can be public, private or internal (members are private by default).
- It includes a constructor without parameters by default and cannot be explicitly created.
Example - Structure Declaration
namespace MyConsoleApp
{
public struct Geocodes
{
public double Latitude;
public double Longitude;
public Geocodes(double latitude, double longitude)
{
Latitude = latitude;
Longitude = longitude;
}
public override string ToString() => $"({Latitude}, {Longitude})";
}
}
Here are the few points to remember when creating an object for the structure.
- An object for a structure can be created with or without using the new operator.
- When creating an object without the new operator, make sure each members have a value assigned to them before accessing them.
- Using the default constructor (without parameters) will initialize the members to their default values based on their types.
Example - Structure Object
namespace MyConsoleApp
{
class Program
{
static void Main(string[] args)
{
//Objects with new operator
Geocodes geo1 = new Geocodes();
Console.WriteLine(geo1.ToString()); //Output: (0, 0)
Geocodes geo2 = new Geocodes(10, 20);
Console.WriteLine(geo2.ToString()); //Output: (10, 20)
//Object without new operator
Geocodes geo3;
geo3.Latitude = 500;
geo3.Longitude = 600;
Console.WriteLine(geo3.ToString()); //Output: (500, 660)
}
}
}
Good To Know
- A structure does not support inheritance i.e. it cannot inherit a class or structure and can't be used as the base of a class.
- Structures can implement interfaces.
- A constructor, when defined, must initialize all the fields declared in the structure.