A structure type (or struct type) is a value type that can encapsulate data and related functionality.
struct
keyword is used to define a structure type.
Typically, you use structure types to design small data-centric types that provide little or no behavior.
Structure types have value semantics. That is, a variable of a structure type contains an instance of the type.
struct |
class |
---|---|
struct cannot be inherited |
class can be inherited |
struct cannot have default constructor |
class can have default constructor |
Value types (of a struct ) that are allocated on the stack or on inline (more performant) |
Reference types (of a class ) are allocated on the heap and garbage-collected |
A struct contains the entire struct, with all its fields. | A class contains pointer to its fields |
Value types (of a struct ) always contains a value |
Reference types (of a class ) can contain a null-reference |
struct are used for small data structures |
class are used for complex data structures |
Copying the contents of a value type variable (a struct ) copies the entire contents into the new variable, making the two distinct |
Copying the contents of a reference type variable (a class ) into another variable copies the reference, the two pointing to the same storage |
After the copy, changes to one won’t affect the other | After the copy, changes to one will affect the other |
struct Employee {
public int id;
public void getId(int id) {
Console.WriteLine("Employee Id: " + id);
}
}
Employee emp;
emp.id = 1;
Console.WriteLine(emp.id);
struct Employee {
public int id;
public Employee(int employeeId) {
id = employeeId;
}
}
Employee emp = new Employee(1);
Console.WriteLine(emp.id);
A struct
can’t be inherited but can inherit from an interface
.
public interface Person
{
string Name { get; set; }
double Age { get; set; }
double GetLifeExpectancy();
}
struct Employee: Person
{
public const int hoursWorked = 35;
public string Name { get; set; }
public double Age { get; set; }
public int id;
public Employee(int employeeId, string name, double age) {
id = employeeId;
Name = name;
Age = age;
}
public double GetLifeExpectancy() {
return(80D - age);
}
}
Employee employee = new Employee(1, "Henry", 33);
Console.WriteLine(emp.GetLifeExpectancy()); // 50
See: