Skip to main content

Structure in C#

A Structure (struct) in C# is a value type data type.

It helps you to create a single variable that can hold related data of different data types.

The struct keyword is used to define a structure.
It is similar to a class, because both are user-defined data types that can store multiple related variables of different data types.
However, unlike classes, structures are value types and are stored in stack memory, not heap.

 

Defining a Structure

In C#, a structure is defined using the struct keyword.
A structure can contain:

·         Fields

·         Constructors

·         Constants

·         Properties

·         Indexers

·         Methods

·         Events

Syntax:

Access_Modifier struct StructureName
{
   // Fields
   // Parameterized constructor
   // Constants
   // Properties
   // Indexers
   // Events
   // Methods
}

 Example: Defining a Structure

struct Books
{
    public string title;
    public string author;
    public string subject;
    public int book_id;
}

Here:

·         Books is the name of the structure.

·         It contains four fields: title, author, subject, and book_id.

Declaring Structure Variables

Before using a structure, we must create a structure variable.
We use the structure name followed by a variable name to declare it.

Example:

struct Books
{
    public int id;
}
 
// Declaring structure variable
Books eng;

Now, eng is a variable of type Books.

You can access and assign values to its members like this:

eng.id = 101;
Console.WriteLine(eng.id);

 Example: Structure with Data

using System;
 
struct Books
{
    public string title;
    public string author;
    public int book_id;
 
    public void Display()
    {
        Console.WriteLine("Title: " + title);
        Console.WriteLine("Author: " + author);
        Console.WriteLine("Book ID: " + book_id);
    }
}
 
class Program
{
    static void Main()
    {
        Books book1;
 
        book1.title = "C# Programming";
        book1.author = "John Doe";
        book1.book_id = 101;
 
        book1.Display();
    }
}

 Output:

Title: C# Programming
Author: John Doe
Book ID: 101

 Features of C# Structures

The main features of C# structures are:

1.       Structures can contain methods, fields, indexers, properties, operator methods, and events.

2.       Structures can have constructors (but not destructors). A default constructor is automatically provided and cannot be defined manually.

3.       Structures cannot inherit from other structures or classes.

4.      Structures cannot be used as a base for other structures or classes.

5.      A structure can implement one or more interfaces.

6.      Structure members cannot be declared as abstract, virtual, or protected.

7.      When you create a struct object using the new keyword, the constructor is called and memory is allocated.

8.      Structs can also be instantiated without using new, but then all fields must be manually initialized before use.

9.       Structures are stored in stack memory, making them faster and lightweight compared to classes.

using System;

 

struct Student

{

    public int id;

    public string name;

}

class Program

{

    static void Main()

    {

        // Using new keyword

        Student s1 = new Student();  // Calls default constructor internally

        Console.WriteLine("Using new keyword:");

        Console.WriteLine("ID: " + s1.id);      // Default value → 0

        Console.WriteLine("Name: " + s1.name);  // Default value → null

        Console.WriteLine();

 

        // Without using new keyword

        Student s2;   // Declaration only (not initialized)

        s2.id = 10;   // Must initialize manually

        s2.name = "Sita";

 

        Console.WriteLine("Without using new keyword:");

        Console.WriteLine("ID: " + s2.id);

        Console.WriteLine("Name: " + s2.name);

    }

}

Differences Difference between Class and Structure

Class

Structure

Classes are reference types.

Structures are value types.

All reference types are allocated on heap memory.

All value types are allocated on stack memory.

Classes have limitless features.

Structures have limited features.

Classes are generally used in large programs.

Structures are used in small programs.

Classes can contain constructors and destructors.

Structures cannot contain parameterless constructors or destructors, but can have parameterized or static constructors.

Classes use the new keyword for creating instances.

Structures can create instances with or without the new keyword.

A class can inherit from another class.

A structure cannot inherit from another structure or class.

The data members of a class can be protected.

The data members of a structure cannot be protected.

The function members of a class can be virtual or abstract.

The function members of a structure cannot be virtual or abstract.

Two variables of a class can contain the reference of the same object, so changes in one affect the other.

Each variable in a structure contains its own copy of data, so changes in one do not affect the other (except in ref or out parameters).


C# program to illustrate the Declaration of structure
using System;
namespace ConsoleApplication
{
    // Defining structure
    public struct Person
    {
        // Declaring different data types
        public string Name;
        public int Age;
        public int Weight;
    };
 
    class Practice
    {
        static void Main(string[] args)
        {
            // Declare P1 of type Person
            Person P1;
 
            // Assign values
            P1.Name = "Sita Thapa";
            P1.Age = 19;
            P1.Weight = 40;
 
            // Displaying the values
            Console.WriteLine("Data Stored in P1 is " +
                              P1.Name + ", age is " +
                              P1.Age + " and weight is " +
                              P1.Weight);
        }
    }
}
Output:
 
Data Stored in P1 is Sita Thapa, age is 19 and weight is 40
 
 
 Example 2: Array of Structures
An array of structures is an array where each element is a structure.
You can initialize and access each structure element individually.
 
using System;
 
struct Person
{
    public string Name;
    public int Age;
}
 
class Program
{
    static void Main()
    {
        // Create an array of structures (size 3)
        Person[] people = new Person[3];
 
        // Initialize each element
        people[0].Name = "Alice";
        people[0].Age = 30;
 
        people[1].Name = "Bob";
        people[1].Age = 25;
 
        people[2].Name = "Charlie";
        people[2].Age = 35;
 
        // Access and display each person's details
        for (int i = 0; i < people.Length; i++)
        {
            Console.WriteLine($"Name: {people[i].Name}, Age: {people[i].Age}");
        }
    }
}
Output:
 
Name: Alice, Age: 30
Name: Bob, Age: 25
Name: Charlie, Age: 35
 
Example 3: Constructor to Initialize the Structure
You can define a constructor inside a structure to initialize its fields directly at the time of object creation.
 
using System;
 
struct Person
{
    public string Name;
    public int Age;
 
    // Constructor to initialize the structure
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
 
    // Method to display person's details
    public void Display()
    {
        Console.WriteLine($"Name: {Name}, Age: {Age}");
    }
}
 
class Program
{
    static void Main()
    {
        // Create and initialize an array of structures
        Person[] people = new Person[3];
        people[0] = new Person("Alice", 30);
        people[1] = new Person("Bob", 25);
        people[2] = new Person("Charlie", 35);
 
        // Display details
        foreach (var person in people)
        {
            person.Display();
        }
    }
}
Output:
 
Name: Alice, Age: 30
Name: Bob, Age: 25
Name: Charlie, Age: 35

Write a structure Employee with EmpID and EmpName. Create two employees and print them.

Write a C# program to store sales of 7 days in an array and calculate the total sales.

Write a program to input marks into an array and display the highest and second highest marks.

Comments

Popular posts from this blog

Function of OS 1. Process Management The operating system helps in running many programs at the same time. It keeps track of each running program (called a process), decides which one should run next, and stops or starts them as needed. It makes sure that all the programs get a fair chance to use the CPU.   2. Memory Management The OS manages the computer's memory (RAM). It decides which program will use how much memory and keeps track of it. When a program is closed, it frees up the memory so that other programs can use it. This helps the computer run smoothly without crashing.   3. File System Management The operating system helps us to create, save, open, and delete files. It organizes files in folders and keeps them safe. It also controls who can open or edit a file to protect our data.   4. Device Management The OS controls all the input and output devices like the keyboard, mouse, printer, and monitor. It tells the devices what to do and makes su...

UNIT 3 Array in C#

  Array in C# An array is a collection of variables of the same data type , stored in contiguous memory locations , and accessed using a common name and index . Each item in an array is called an element , and the index of arrays in C# starts from 0 .     Key Points About Arrays in C#: 1.       Elements are stored in contiguous memory locations. 2.       Index starts from 0. So, for an array of size 5, valid indexes are 0 to 4. 3.       Arrays are reference types and are allocated on the heap. 4.       C# array is an object of base type System.Array . 5.       Array elements can be of any type , including another array (array of arrays). 6.       Jagged array (array of arrays) elements are reference types and are initialized to null . 7.       Arrays can be single-dimensi...

Unit 2 Java

Data Types A data type defines the kind of data a variable can store, the operations that can be performed on it, and the amount of memory allocated. Java Primitive Data Types Data Type Size Range (Approx.) Example Byte 1 byte -128 to 127 byte a = 100; short 2 bytes -32,768 to 32,767 short s = 1000; Int 4 bytes -2,147,483,648 to 2,147,483,647 int num = 50000; Long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 long l = 100000L; float 4 bytes ~6–7 decimal digits float f = 5.75f; double 8 bytes ~15 decimal digits double d = 19.99; Char 2 bytes Single Unicode character char c = 'A'; boolean 1 bit* tru...