C# Structures (Structs)

In c#, structures are same as classes but only difference is classes are the reference types and structures are the value types. As a value type, the structures directly contain their value so their object or instance is stored on the stack and structures are faster than classes.

 

In c#, the structures can contain a fields, properties, member functions, operators, constructors, events, indexers, constants and even other structure types.

Declaring a Structures in C#

In c#, structures are declared by using struct keyword. Following is the declaration of structure in c# programming language.

 

public struct users

{

// Properties, Methods, Events, etc.

}

If you observe above syntax, we defined a structure “users” using struct keyword with public access modifier. Here, the public access specifier will allow the users to create an objects for this structure and inside of the body structure, we can create a required fields, properties, methods and events to use it in our applications.

 

Following is the example of defining a structure in c# programming language.

 

public struct User

{

    public string name;

    public string location;

    public int age;

}

If you observe above example, we defined a structure called “User” with required fields and we can add required methods and properties based on our requirements.

C# Structure Initialization

In c#, structures can be instantiated with or without new keyword. Following is the example of assigning a values to the variables of structure.

 

User u = new User();

u.name = "Suresh Dasari";

u.location = "Hyderabad";

u.age = 32;

To make use of fields, methods and events of structure, then it’s mandatory to instantiate a structure with new keyword in c# programming language.

C# Structure with Constructor

In c#, the structures won’t allow us to declare a default constructor or a constructor without parameters and it won’t allow us to initialize a fields with values unless they are declared as const or static.

 

Following is the example of defining a structure with parameterized constructor and initializing the fields in constructor in c# programming language.

 

public struct User

{

    public string name, location;

    // Parameterized Constructor

    public User(string a, string b)

    {

        name = a;

        location = b;

    }

}

If you observe above example, we defined a structure called “User” with required fields and parameterized constructor.

C# Structure with Default Constructor

As discussed, the structures will allow only parameterized constructors and fields cannot be initialized unless they are declared it as const or static.

 

Following is the example of defining a structure with default constructor and initializing a fields with values.

 

struct User

  {

   // Compile error

      public string name = "Suresh Dasari";

      public string location;

      public int age;

      // Compile error

      public User()

      {

          location = "Hyderabad";

          age = 32;

      }

  }

When we execute above code we will get a compiler errors because we declared a structure with default constructor (parameter less) and initialized a fields without defining it as const or static.

 

In c#, if we create a structure with parameterized constructor, then we must need to explicitly initialize all the fields with in the constructor before the control is returned to the caller otherwise we will get a compile time error.

 

Following is the example of defining a structure with parameterized constructor and required fields in c# programming language.

 

public struct User

{

    public string name, location;

    // Compile Error

    public User(string a)

    {

        name = a;

    }

}

When we execute above code, we will get a compile time error because we defined a name and location variables but we are assigning a value to only name variable.

 

As discussed, if we create a structure with parameterized constructor, then we must need to explicitly initialize all the fields before leaving the constructor.

 

Now we will see how to create a structure with fields and parameterized constructor in c# programming language with example.

C# Structure Example

Following is the example of creating a structure with different type of fields and parameterized constructor in c# programming language with various data members and member functions.

 

using System;

 

namespace Tutlane

{

    struct User

    {

        public const string name = "Suresh Dasari";

        public string location;

        public int age;

        public User(string a, int b)

        {

            location = a;

            age = b;

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            // Declare object with new keyword

            User u = new User("Hyderabad", 31);

            // Declare object without new keyword

            User u1;

            Console.WriteLine("Name: {0}, Location: {1}, Age: {2}", User.name, u.location, u.age);

            // Initialize Fields

            u1.location = "Guntur";

            u1.age = 32;

            Console.WriteLine("Name: {0}, Location: {1}, Age: {2}", User.name, u1.location, u1.age);

            Console.WriteLine("\nPress Enter Key to Exit..");

            Console.ReadLine();

        }

    }

}

If you observe above example, we defined a structure (User) by including a required fields, parameterized constructor and created an instance of structure (User) with and without new keyword to initialize or get field values based on our requirements.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Structures Example Result

 

In c#, by using structures we can implement an interface but structures cannot inherit from another structure or class.

C# Structure Characteristics

Following are the important characteristics of structures in c# programming language.

 

  • In c#, structures are value types and those are defined by using struct keyword.
  • During structure declaration, the fields cannot be initialized unless they are defined as const or static.
  • Structures in c# can include fields, properties, member functions, operators, constructors, events, indexers, constants and even other structure types.
  • Structures cannot include default constructor (constructor without parameters) or destructor but it will allow us to declare constructors with parameters.
  • A structure cannot inherit from another structure or class.
  • In c#, the structure can implement interfaces.
  • A structure can instantiated with or without using a new keyword.

C# Difference between Structure and Class

Following are the difference between structures and classes in c# programming language.