In C#, classes and structs are blueprints that are used to create instance of a class. Structs are used for lightweight objects such as Color, Rectangle, Point etc.
Unlike class, structs in C# are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct.
Let’s see a simple example of struct Rectangle which 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)); } }
Output:
Area of Rectangle is: 20
Enum in C# is also known as enumeration. It is used to store a set of named constants such as season, days, month, size etc. The enum constants are also known as enumerators. Enum in C# can be declared within or outside class and structs.
Enum constants has default values which starts from 0 and incremented to one by one. But we can change the default value.
Points to remember:
Let’s see a simple example of C# enum.
using System; public class EnumExample { public enum Season { WINTER, SPRING, SUMMER, FALL } public static void Main() { int x = (int)Season.WINTER; int y = (int)Season.SUMMER; Console.WriteLine("WINTER = {0}", x); Console.WriteLine("SUMMER = {0}", y); } }
Output:
WINTER = 0 SUMMER = 2
We can also change the starting index, see the below code.
public enum Season { WINTER=10, SPRING, SUMMER, FALL }
In order to traverse all values we can use getNames() or getValues() methods.
using System; public class EnumExample { public enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; public static void Main() { foreach (string s in Enum.GetNames(typeof(Days))) { Console.WriteLine(s); } } }
Output:
Sun Mon Tue Wed Thu Fri Sat
Try the following example in the editor below.
Create a structure named ‘student
’, containing three members: name (string), rollno(int) and marks(int).