Saturday, May 13, 2023

Struct in c#| Enum in C#| Struct and Enum in C#

What is struct and enum in c#?


 In C#, a struct and an enum are two different types of value types that are used to define custom data types with specific characteristics.


A struct is a value type that can contain data members and member functions (methods). It is similar to a class, but it is typically used for small data structures that can be efficiently passed by value. Structs are generally used when performance is a primary concern, or when you want to define a lightweight data type that doesn't require the overhead of a full-blown class. Here is an example of a struct in C#:



struct Point

{

    public int X;

    public int Y;


    public Point(int x, int y)

    {

        X = x;

        Y = y;

    }

}



In this example, we define a struct called "Point" that contains two integer data members, "X" and "Y", and a constructor that initializes them. We can create instances of this struct using the "new" operator, like this:



Point p = new Point(10, 20);



An enum, on the other hand, is a value type that represents a set of named constants. It is used to define a finite set of related values that can be used in place of literal values throughout your code. Enums are typically used to improve code readability and maintainability by providing a well-defined set of named values. Here is an example of an enum in C#:



enum DayOfWeek

{

    Sunday,

    Monday,

    Tuesday,

    Wednesday,

    Thursday,

    Friday,

    Saturday

}



In this example, we define an enum called "DayOfWeek" that contains seven named values, one for each day of the week. We can use these named values throughout our code to represent the days of the week, like this:



DayOfWeek today = DayOfWeek.Wednesday;


Both structs and enums are value types in C#, which means that they are stored directly in memory and copied by value when passed to methods or assigned to variables. They can be used to define custom data types that have specific characteristics and behavior, and are often used in conjunction with classes to provide a complete object-oriented programming experience.

No comments:

Post a Comment

If you have any query kindly let me know.

Blazor drawback| drawback of blazor| Disadvantage of blazor in c#

  Blazor drawback| drawback of blazor| Disadvantage of blazor in c# While Blazor offers many advantages, it also has a few drawbacks to cons...