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

Collections in C#

Collections in C# In our previous article , we have learned about how we can use arrays in C#. Arrays in programming are used to group a set of related objects. So one could create an array or a set of Integers, which could be accessed via one variable name. What is Collections in C#? Collections are similar to Arrays, it provides a more flexible way of working with a group of objects. In arrays, you would have noticed that you need to define the number of elements in an array beforehand. This had to be done when the array was declared. But in a collection, you don't need to define the size of the collection beforehand. You can add elements or even remove elements from the collection at any point of time. This article will focus on how we can work with the different collections available in C#. There are three distinct collection types in C#: standard generic concurrent The standard collections are found under the System.Collections. They do not store elemen...

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...

System.IO Namesapce in C#

  System.IO Namesapce in C# A  file  is a collection of data stored in a disk with a specific name and a directory path. When a file is opened for reading or writing, it becomes a  stream . The stream is basically the sequence of bytes passing through the communication path. There are two main streams: the  input stream  and the  output stream . The  input stream  is used for reading data from file (read operation) and the  output stream  is used for writing into the file (write operation). From the above definition of file, the C# provides a namespace that enable us to manipulate file in C# called System.IO.   System.IO  is a  namespace  and it contains a standard IO (input/output) types such as classes , structures , enumerations , and  delegates  to perform a read/write operations on different sources like file, memory, network, etc.   System.IO Classes The table below shows differen...