structure in C# with Example

Shahzad Aslam
2 min readMay 1, 2024

A struct a value type and it store it’s data in stack. Classes are reference type and it store it’s data in heap. The structs are usually used for small data structures. The structssare specially used when we don’t need features of classes like inheritance.

structure in C# with Example

Struct in C# with Example

using System;
public class Program
{
public static void Main(string[] args)
{
Fruit p1 = new Fruit(10, "Mango", true);
Fruit p2 = p1; // Creates a copy of p1
p2.FruitPrice = 30; // Modifying p2 does not affect p1
Console.WriteLine($"p1: ({p1.FruitPrice}, {p1.FruitName}, {p1.FruitIsInMarket})"); // Output: p1: (10, 20)
Console.WriteLine($"p2: ({p2.FruitPrice}, {p2.FruitName}, {p1.FruitIsInMarket})"); // Output: p2: (30, 20
}
}

public struct Fruit
{
// Struct Fields
public int FruitPrice;
public string FruitName;
public bool FruitIsInMarket;

// Struct Constructor
public Fruit(int price, string name, bool isavailable)
{
// Initialization code for struct members
FruitPrice = price;
FruitName = name;
FruitIsInMarket = isavailable;
}

// Struct Method
public int AddFruit(int price1, int price2)
{
return price1 + price2;
}
}

Output

p1: (10, Mango, True)
p2: (30, Mango, True)

Value Type:

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

Responses (1)