Topic : Structure In C# Programming Language: |Struct Keyword|

Introduction to C# Structures:

A structure is a collection of one or more variable types. As we know, each element in an Array must be the same data type, and we must refer to the entire array by its name. Each element (Called a Member) in a structure can be a different data type. The structure is another user-defined data type which allows us to combine data items of different kinds.

Structure are used to represent a record, suppose we want to keep track of Our books in a library. We might want to track the following attributes about each book.


  • » Title:
    » Author:
    » Subject:
    » Book ID:


There would be four Members in this Library Structure. After deciding on the Members, we must decide what data type each member is. The title Author and subject are character arrays, The Book ID is an integer and so on.



Member NameData Type
Title: Character Array of 25 Characters.
Author: Character Array of 20 Characters.
Subject: Character Array of 25 Characters.
Book ID: Array of Integers:


Each structure we define can have an associated structure name called a Structure tag. Structure tags are not required in most cases, but it is generally best to define one for each structure in Our program. The structure tag is not a variable name. Unlike array names, which reference the array as variables, a structure tag is simply a label for the structure's format.



Although both contain the term "Structure", Control Structure and Data Structure are very different. The Control structure sequence, selection, and loop describe the logical flow of a program's instructions. Data Structure is used to encapsulate separate related data fields.



Defining a Structure:

Structures are Syntactically defined with the word Struct. so Struct is another keyword that cannot be used as variable name. Followed by the name of the structure. The data, contained in the structure, is defined in the curly braces. All the variables that we have been using can be part of structure. For Example:



struct structure_Tag
{
   Access_Specifier  DataType1  Element1;
   Access_Specifier  DataType2  Element2;
   Access_Specifier  DataType3  Element3;
   ...
   ...
   Access_Specifier  DataTypeN  ElementN;
};



The Semicolon after the closing curly brace in the struct definitions is important. Our program will not compile without it. Unfortunately, this semicolon is easy to forget, because when closing curly braces appear in other places in C# programs. (For Example, at the end of Methods) they are seldom followed by a semicolon.


  • In Above Syntax:

    » Struct is the keyword to declare the Structure in C#:
    » Structure_Tag is a Name for the Model of the structure Type. We need to name Structure_Tag our self using the same Naming rules for Variables:
    » Access_Specifier Describes as the scope of Accessibility the Structure Elements: it could be Public, private or protected:
    » DataType is the valid data type, could be any like int, char, or float.
    » and Element is the variable name for that elements to be store.



Example:

Let's have an example to know how we can declare the structure using struct keyword in C# and how we can use it:


/*Example: Structure in C#: InfoBrother:*/

using System;

namespace DataStructure
{
    class Program
    {
        struct book   //structure declare:
        {      //elements:
            public string title;
            public string author;
            public int book_id;
            public float price;
        };


        static void Main(string[] args)
        {
            book book1;  //Declare book1 of type book;

            Console.WriteLine("Enter Book Name: ");
            book1.title = Console.ReadLine();

            Console.WriteLine("Enter Author Name: ");
            book1.author = Console.ReadLine();

            Console.WriteLine("Enter Book ID: ");
            book1.book_id = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter Book Price: ($)");
            book1.price = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("\n");

            //display the data:
            Console.WriteLine("Book Name: " + book1.title);
            Console.WriteLine("Book Author: " + book1.author);
            Console.WriteLine("Book ID: " + book1.book_id);
            Console.WriteLine("Book Price: $" +book1.price);

            Console.ReadKey();
        }
    }
}


  • Features of C# Structure:

    The C# Structure are Quite Different from the C or C++ Structures. The C# structures have the following features:

    » Structures can have defined constructors, but not destructors. However, We cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed.
    » Structures can have methods, fields, indexers, properties, operator methods, and events.
    » Unlike classes, structures cannot inherit other structures or classes.
    » Structures cannot be used as a base for other structures or classes.
    » A structure can implement one or more interfaces.
    » Structure members cannot be specified as abstract, virtual, or protected.
    » When We create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator.
    » If the New operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized.



  • Class Vs Struct:

    » Classes are Reference types and Structures are Values types.
    » Classes will support an Inheritance whereas Structures won’t.
    » Classes can have explicitly parameter less constructors whereas structures can’t.
    » Member variable initialization is possible in class whereas in Structures, it is not.
    » It is not possible to declare destructor in structure but in class it is possible.



Example:

Let's have another Example using structure. in this example, we will create some methods to get and display some students record. its very easy and conceptual example to understand the concept of structure in C#:


/*Example: Structure in C#: InfoBrother:*/

using System;

namespace DataStructure
{
    class Program
    {
        struct Student   //structure declare:
        {      //elements:
            public string Name;
            public int age;
            public string position;
            public int clas;

            //methods to get data:
            public void getData(string N, int a, string p, int c)
            {
                Name = N;
                age = a;
                position = p;
                clas = c;
            }

            public void display() //display method:
            {
                Console.WriteLine("{0} is {1} year old. and He Got {2} Position in class {3}"
                    ,Name, age, position, clas);
            }
        };


        static void Main(string[] args)
        {
            Student stu1 = new Student(); //Declare stu1 of type student:
            Student stu2 = new Student(); //Declare stu2 of type student;

            stu1.getData("Ali", 17, "2nd", 10); //get data Method:
            stu2.getData("John", 18, "1st", 10); //get data Method:

            stu1.display(); //display data method:
            stu2.display(); //display data method:

            Console.ReadKey();
        }
    }
}


n general, classes can be used when we have more complex behavior or data. And if you think that this behavior or data to be modified after creating an instance of the class, then classes are absolute methods.
Structures can be used for small data structures. If the developer feels that data members of the structure cannot be modified after creating structure, then having structure will suit.
















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement