C#-Structs

Structs in C#

A C#-Structs type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory.

The following example shows a simple struct declaration:

struct Book {
  public string title;  
  public double price;
  public string author;
}

C# Struct Example

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));
    }
}

C#-Structs Example: Using Constructor and Method

Let’s see another example of struct where we are using constructor to initialize data and method to calculate area of rectangle.

using System;
public struct Rectangle
{
    public int width, height;

    public Rectangle(int w, int h)
    {
        width = w;
        height = h;
    }
    public void areaOfRectangle() { 
     Console.WriteLine("Area of Rectangle is: "+(width*height)); }
    }
public class TestStructs
{
    public static void Main()
    {
        Rectangle r = new Rectangle(5, 6);
        r.areaOfRectangle();
    }
}

Structs vs Classes :

In general, classes are used to model more complex behavior, or data, that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created. Consider defining a struct instead of a class if you are trying to represent a simple set of data.


Recommended Posts:

Spread the love

Leave a Comment

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