Structs (C# vs Java)
C# supports the struct keyword, another item that originates in C but is not available in Java. You can think of a struct as a lightweight class. It can contain constructors, constants, fields, methods, properties, indexers, operators, and nested types in much the same way as a class. structs differ from classes in that they cannot be abstract and do not support implementation inheritance. The important difference from a class is that structs are value types, while classes are reference types. There are some differences in the way constructors work for structs. In particular, the compiler always supplies a default no-parameter constructor, which you are not permitted to replace.
In the following example, you initialize a struct with the newkeyword, calling the default no-parameter constructor, and then set the members of the instance.
public struct Customer
{
public int ID;
public string Name;
public Customer(int customerID, string customerName)
{
ID = customerID;
Name = customerName;
}
}
class TestCustomer
{
static void Main()
{
Customer c1 = new Customer(); //using the default constructor
System.Console.WriteLine("Struct values before initialization:");
System.Console.WriteLine("ID = {0}, Name = {1}", c1.ID, c1.Name);
System.Console.WriteLine();
c1.ID = 100;
c1.Name = "Robert";
System.Console.WriteLine("Struct values after initialization:");
System.Console.WriteLine("ID = {0}, Name = {1}", c1.ID, c1.Name);
}
}
Output
When we compile and run the previous code, its output shows that struct variables are initialized by default. The int variable is initialized to 0, and the string variable to an empty string:
Struct values before initialization:
ID = 0, Name =
Struct values after initialization:
ID = 100, Name = Robert
If Customer
had been declared as a class instead of a struct, the no-parameter constructor would not have been provided, and the following line of code would have caused a compile error:
Customer c1 = new Customer(); //using the default constructor
See Also
Tasks
Concepts
C# Programming Guide
Structs (C# Programming Guide)