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. Although structs can contain constructors, constants, fields, methods, properties, indexers, operators, and nested types, they are mostly used simply to encapsulate groups of related fields. Because structs are value types, they can be allocated slightly more efficiently than classes. structs differ from classes in that they cannot be abstract and do not support implementation inheritance.

In the following example, you initialize a struct with the new keyword, 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);

        c1.ID = 100;
        c1.Name = "Robert";

        System.Console.WriteLine("Struct values after initialization:");
        System.Console.WriteLine("ID = {0}, Name = {1}", c1.ID, c1.Name);

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

Community Additions