Definition of Structure

A structure is a group of variables of different data types combined into one single unit. It is similar to a class because both are user-defined data types. Both can store different types of data together. In C#, a structure is a composite data type. This means it can contain many elements of different types. A structure in C# is a value type. The objects (instances) of a structure are stored in the stack memory.

A structure can contain:

  • Fields
  • Methods
  • Constants
  • Constructors
  • Properties
  • Indexers
  • Operators
  • Even other structures

The struct keyword is used to create a structure in C#.

Why We Use Structure

Structures are used to represent a record. For example, suppose you want to store information about books in a library. You may need to store:

  • Title
  • Author
  • Subject
  • Book ID
    All these details belong to one book. So, we can group them together using a structure.

Syntax of Structure

struct Student {
public string name;
public int id;
public string subject;
};

In this example, name and subject are of type string, and id is of type int. These different data types are grouped together in one structure called Student to store related student information in an organized way.

Features of C# Structures

You have already used a simple structure named  Student. Structures in C# are quite different from that in traditional C or C++.

The C# structures have the following features −

  • Structures can have methods, fields, indexers, properties, operator methods, and events.
  •  Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and cannot be changed.
  •  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 you 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.

Example 1: C# Structure

Let us see a simple example of a C# structure. In this example, we create a structure named Rectangle. It has two data members: width and height.

using System;
public struct Rectangle
{
public int width, height;
}
public class TestStructs
{
public static void Main()
{
Rectangle r = new Rectangle();
r.width = 4;
r.height = 5;
Console.WriteLine("Area of Rectangle is: " + (r.width * r.height));
}
}
The output of this code: 20

Explanation of code :

A rectangle is a structure that contains two integer variables named width and height. In the Main() method, we create an object r of the Rectangle structure. We then assign the values width = 4 and height = 5 to the object. After that, we calculate the area of the rectangle using the formula Area = width × height. Finally, the result is displayed on the screen using the Console.WriteLine() method.

Question 1: Write a C# program to create a structure student with data members name, roll, and marks. Display the student’s details.

using System;
public struct Student
{
public string name;
public int roll;
public float marks;
}
public class TestStudent
{
public static void Main()
{
Student s1;
s1.name = "Basant";
s1.roll = 10;
s1.marks = 85.5f;
Console.WriteLine("Student Name: " + s1.name);
Console.WriteLine("Roll Number: " + s1.roll);
Console.WriteLine("Marks: " + s1.marks);
}
}

In this program, we created a structure named Student. The structure contains three data members: name, roll, and marks. Inside the Main() method, we created a structure variable called s1. After creating the variable, we assigned values to its members such as the student’s name, roll number, and marks. Finally, we displayed these values on the screen using the Console.WriteLine() method. This program demonstrates how to define a structure, create its object, assign values, and print the data in C#.

Question 2: Write a C# program to create a structure Rectangle and calculate the area.

using System;
public struct Rectangle
{
public int width;
public int height;
public int Area()
{
return width * height;
}
}
public class TestRectangle
{
public static void Main()
{
Rectangle r;
r.width = 4;
r.height = 5;
Console.WriteLine("Width: " + r.width);
Console.WriteLine("Height: " + r.height);
Console.WriteLine("Area: " + r.Area());
}
}

In this program, we created a Rectangle structure with two integer variables: width and height. It has a method Area() that calculates and returns the area using width × height. In the Main() method, we assigned values, called Area(), and printed the result

Question 3: Write a C# program to create a structure Employee and display the salary after adding a bonus.

using System;
public struct Employee
{
public string name;
public double salary;
public double AddBonus(double bonus)
{
return salary + bonus;
}
}
public class TestEmployee
{
public static void Main()
{
Employee e1;
e1.name = "Ram";
e1.salary = 30000;
double totalSalary = e1.AddBonus(5000);
Console.WriteLine("Employee Name: " + e1.name);
Console.WriteLine("Original Salary: " + e1.salary);
Console.WriteLine("Salary after Bonus: " + totalSalary);
}
}

In this example, we created an Employee structure with two members: name and salary. It includes a method AddBonus() that adds a bonus to the salary. The final salary is then calculated and displayed.

Question 4: Create a structure Book with title, author, and price. Display the details of a book.

using System;
public struct Book
{
public string title;
public string author;
public double price;
}
public class TestBook
{
public static void Main()
{
Book b1;
b1.title = "Introduction to C#";
b1.author = "Basant Kumar";
b1.price = 450.50;
Console.WriteLine("Book Title: " + b1.title);
Console.WriteLine("Author: " + b1.author);
Console.WriteLine("Price: $" + b1.price);
}
}

In this program, we first define a structure named Book which groups three related data members: title, author, and price. This structure allows us to treat a book as a single unit containing all relevant information. In the Main() method, we create a variable b1 of type Book. We then assign values to each member of the structure. UsingConsole.WriteLine(), we display all the information together. This demonstrates how structures can be used to logically group related data and make the program more organized.

Question 5: Create a structure Circle to calculate the area and circumference of a circle.

using System;
public struct Circle
{
public double radius;
public double Area()
{
return 3.14159 * radius * radius;
}
public double Circumference()
{
return 2 * 3.14159 * radius;
}
}
public class TestCircle
{
public static void Main()
{
Circle c1;
c1.radius = 7.5;
Console.WriteLine("Radius: " + c1.radius);
Console.WriteLine("Area: " + c1.Area());
Console.WriteLine("Circumference: " + c1.Circumference());
}
}

Here, we define a structure Circle with a single member radius. We also define two methods inside the structure: Area() and Circumference(). The Area() method calculates the area using the formula π × r², and the Circumference() method calculates the circumference using 2 × π × r. In the Main() method, we create a variable c1 of type Circle, assign a value to its radius, and then call the two methods to calculate and display the area and circumference. This example shows that structures can contain not only data but also methods, making them very useful for small and logically related operations.

What Is Class?

A class is a user-defined blueprint or prototype from which objects are created. It combines fields (data) and methods (functions that define actions) into a single unit. Essentially, a class acts as a model for creating objects, encapsulating both data and behavior in one structure.

Example : (C# with class)

// C# program to illustrate the concept of class
using System;
// Class Declaration
public class Author
{
// Data members of class
public string name;
public string language;
public int article_no;
public int improv_no;
// Method of class
public void Details(string name, string language, int article_no, int improv_no)
{
this.name = name;
this.language = language;
this.article_no = article_no;
this.improv_no = improv_no;
Console.WriteLine("The name of the author is : " + name +
"\nThe name of language is : " + language +
"\nTotal number of article published " + article_no +
"\nTotal number of Improvements: done by author is : " + improv_no);
}
// Main Method
public static void Main(String[] args)
{
// Creating object
Author obj = new Author();
// Calling method of class using class object
obj.Details("Ankita", "C#", 80, 50);
}
}

Output:

The name of the author is : Ankita
The name of language is : C#
Total number of article published 80
Total number of Improvements: done by author is : 50

Comparison Between Class and Structure in C#

ClassStructure (Struct)
Reference types are stored on heap memory (reference stored on stack).Value types are usually stored on stack memory.
Considered as reference types.Considered as value types.
Allocation of large reference types is more efficient than large value types.Allocation is more efficient for small value types than reference types.
Usually used in large programs.Usually used in small programs.
Contains many features (inheritance, polymorphism, etc.).Has restricted features compared to class.
Can include constructors and destructors.Cannot contain destructors and cannot define a custom parameterless constructor.
Requires the new keyword to create an instance.Can be created without using the new keyword.
Can inherit from another class.Cannot inherit from another class or struct (but can implement interfaces).
Data members can be protected, private, or public.Data members cannot be protected (only public or private).

Enumeration (Enums)

An enumeration is a set of named integer constants. An enumerated type is declared using the enum keyword. C# enumerations are value data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.

Declaring an Enum Variable
The general syntax for declaring an enumeration (enum) is:
enum <enum_name> { value1, value2, value3, ... };

An enumeration (enum) is a user-defined data type. The enum_name is the name of the enumeration type. The values inside { } are called enumerators, and they are separated by commas. Each enumerator represents an integer value. By default, the first value is 0, and the next values increase automatically by 1.

For example, in enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };, Days is the name of the enumeration type. The values inside the curly braces { } are called enumerators: Sun, Mon, Tue, Wed, Thu, Fri, and Sat. By default, Sun is assigned the value 0, Mon is 1, Tue is 2, and this continues up to Sat, which is assigned 6 automatically.

Example of Enum in C++

Here is a simple example of using an enumeration:

#include <iostream>
using namespace std;
// Declaring enum
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
int main() {
Days today; // Declare enum variable
today = Wed; // Assign value
cout << "The value of today is: " << today;
return 0;
}

In this example, an enum named Days is declared with the days of the week. By default, the first value Sun is assigned 0, and the rest increase automatically by 1. A variable of type Days is created and assigned Wed. When printed, it shows the integer value 3, because enum values are stored internally as numbers.

Write a C# program that creates an enumeration named Months with the values January, February, March, April, May, and June. Assign one month to a variable and display both the name of the month and its corresponding integer value on the screen.

using System;
class Program
{
// Declaring enum
enum Months { January, February, March, April, May, June }
static void Main()
{
// Create a variable of type Months
Months currentMonth = March;
// Display the name of the month
Console.WriteLine("Month Name: " + currentMonth);
// Display the corresponding integer value
Console.WriteLine("Month Number: " + (int)currentMonth);
}
}

Compiled By Er. Basant Kumar Yadav

Leave a Comment

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

error: Content is protected !!
Scroll to Top