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

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...