Skip to main content

Structures in C# explained

Structures in C# explained

Structures (structs) are same as classes but the 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.

 The structures can contain fields, properties, member functions, operatorsconstructors, events, indexers, constants and even other structure types.

 Creating Structures in C#

Structures can be created by using struct keyword in C#. Following code shows the declaration of structure in the C#.

 public struct user

{

   // Properties, Methods, Events, etc.

}

 

From the above syntax, we defined a structure “users” using struct keyword with public access modifier. The public access specifier will allow the users to create objects for this structure and inside of the body structure, we can create required fields, properties, methods and events to use.

 

The code below shows an example of defining a structure in C#.

 

public struct User

{

    public string name;

    public string location;

    public int age;

}

 

Structure Initialization

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

 

User u = new User

{

     name = "Musa Sule Gadabs",

     location = "Abuja",

     age = 42

};

 

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

 Structure with Constructor

The structure won’t allow us to declare a default constructor or a constructor without parameters and it won’t allow us to initialize fields with values unless they are declared as const or static.

 

The code below shows example of defining a structure with parameterized constructor and initializing the fields in constructor.

 

    public struct User

    {

        public string Name;

        public string Location;

        // Parameterized Constructor

        public User(string name, string location)

        {

            Name = name;

            Location = location;

        }

    }

 

Structure with Default Constructor

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

 

Below is an example of defining a structure with a default constructor and initializing fields with values.

 

    struct User

    {

        // Compile error

        public string name = "Musa Sule";

        public string location;

        public int age;

        // Compile error

        public User()

        {

            location = "Abuja";

            age = 42;

        }

    }

 

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.

 

If we create a structure with the parameterized constructor, then we must need to explicitly initialize all the fields within 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 the parameterized constructor and required fields in C#.

 

     public struct User

    {

        public string Name, Location;

        // Compile Error

        public User(string name)

        {

            Name = name;

        }

    }

 

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

 

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

 

Structure Example in C#

The following example create a structure with different types of fields and parameterized constructors in C# with various data members and member functions.

 

using System;

namespace CsharpnaijaTutorial

{

    struct User

    {

        public const string name = "Musa Sule";

        public string Location;

        public int Age;

        public User(string location, int age)

        {

            Location = location;

            Age = age;

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            // Declare object with new keyword

            User user = new User("Abuja", 41);

            // Declare object without new keyword

            User user1;

            Console.WriteLine($"Name: {User.name}, Location: {user.Location}, Age: {user.Age}");

            // Initialize Fields

            user1.Location = "Durumi II";

            user1.Age = 42;

            Console.WriteLine($"Name: {User.name}, Location: {user1.Location}, Age: {user1.Age}");

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

            Console.ReadLine();

        }

    }

}

 

If you observed from the 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.

 

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

Structure
 


Structure Characteristics

 

The following are the important characteristics of structures in C#.

 

  • Structures are value types and those are defined by using struct keyword.
  • During the 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.
  • Structure can implement interfaces.
  • A structure can be instantiated with or without using a new keyword.

Difference between Structure and Class

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

 

  • In C#, classes are the reference types and structures are the value types.
  • Classes can contain default constructor or destructor but structures will contain only constructors that have parameters.
  • We can implement inheritance using Classes but structures won’t support inheritance.
  • Unlike classes, structs can be instantiated with or without using a new operator.

References

1.     Tutlane

2.     CsharpCorner

 

 

 

 

 

 


Comments

Popular posts from this blog

The String.Join Method in C# Explained

The String.Join Method in C#   The string.Join concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member. Overloads of string.Join Method Description Join(Char, Object[]) Concatenates the string representations of an array of objects, using the specified separator between each member. Join(Char, String[]) Concatenates an array of strings, using the specified separator between each member. Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member. Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element. Join(String, String[]) Concatenates all the elements of a string array, usi...

Most Popular Programming Languages in 2020

Most Popular Programming Languages in 2020 In this blog post, you will learn about the most popular programming languages in 2020 for creating the best web applications. Check its pros and cons. Analyzed by technostacks Not very long ago, just a few people were considered to be computer programmers, and the general public viewed them with awe. In this digital age that we are now living in, however, a large number of IT jobs need a solid grasp of one or more programming languages. Whether one wants to develop a mobile app or get a certification for having programming knowledge, or even to learn new skills, one needs to opt for the right programming language. Below mentioned eight most popular programming languages which are in demand for software development and web applications. This is the most used programming languages in 2019 and will be in 2020. For each, there is little information about the language, benefits and its complexity, as well as about its usage. One must...

HashTable in C# with Example

  HashTable in C# with Example Hashtable  is used to store a collection of key/value pairs of different  data types  and are organized based on the hash code of the key.   Generally, the hashtable object will contain buckets to store elements of the collection. The bucket here, is a virtual subgroup of elements within the hashtable and each bucket is associated with a hash code, which is generated based on the key of an element.   In C#, hashtable is same as a  dictionary  object but the only difference is that the  dictionary  object is used to store a key-value pair of same  data type  elements.   When compared with  dictionary  object, the hashtable will provide a lower performance because the hashtable elements are of object type so the boxing and unboxing process will occur when we are storing or retrieving values from the hashtable.   C# HashTable Declaration Hashtable is a non-generic type...