Structure (C#)

In this article i am explaining about structure.Structure is the value type data type that can contain variables, methods, properties, events and etc. It simplifies the program and enhance performance of code in C# programming.

The structure encapsulate small group of related variables inside a single user-defined data type. It improves speed and memory usage and also enhances performance and clarity of your code.

How to use structure in C#?

It is very simple to use structure in C#. The following programming example will show you to how to create and use structure in C# programming.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Structure_Statements
{
    class Program
    {
        // creating three different variable in single structure
        struct Book
        {
            public string BookName
            public int Price;
            public string Category;
        }
        static void Main(string[] args)
        {
            //Creating two book type variable
            Book language, database;
            // Storing value in language variable
            Console.Write("Enter book name:\t");
            language.BookName = Console.ReadLine();
            Console.Write("Enter book price:\t");
            language.Price = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter book category:\t");
            language.Category = Console.ReadLine();
            //Storing value in database variable
            Console.Write("\n\nEnter book name:\t");
            database.BookName = Console.ReadLine();
            Console.Write("Enter book price:\t");
            database.Price = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter book category:\t");
            database.Category = Console.ReadLine();
            //Displaying value of language variable
            Console.Write("\n\n===================");
            Console.Write("\n\t\tLanguage\n");
            Console.Write("===================\n\n");
            Console.Write("Book Name:\t{0}", language.BookName);
            Console.Write("\nBook Price:\t{0}", language.Price);
            Console.Write("\nBook Category:\t{0}", language.Category);
            Console.Write("\n\n==================\n");
            Console.Write("\t\tDatabase\n");
            Console.Write("====================\n\n");
            Console.Write("Book Name:\t{0}", database.BookName);
            Console.Write("\nBook Price:\t{0}", database.Price);
            Console.Write("\nBook Category:\t{0}", database.Category);
            Console.ReadLine();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *