top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Explain about Structure in C#

0 votes
285 views

We have learned class in the previous section. Class is a reference type. C# includes a value type entity, which is called Structure. A structure is a value type that can contain constructors, constants, fields, methods, properties, indexers, operators, events and nested types. A structure can be defined using the struct keyword.

Example: Structure

public struct Discounts
{
    public int Cloths { get; set; }
    public int HomeDecor { get; set; }
    public int Grocery { get; set; }
}

A struct can be initialized with or without the new keyword same as primitive variable or an object. You can then assign values to the members of the structure as shown below.

Example: Initialize a structure

            
Discounts saleDiscounts;

saleDiscounts.Cloths = 10;
saleDiscounts.HomeDecor = 5;
saleDiscounts.Grocery = 2;

A struct is a value type so it is faster than a class object. Use struct whenever you want to just store the data. Generally structs are good for game programming. However, it is easier to transfer a class object than a struct. So do not use struct when you are passing data across the wire or to other classes.

Example: structure

struct Point
{
    private int _x, _y;

    public int x, y;

    public static int X, Y;

    public int XPoint {
        get 
        {
              return _x;
        }

        set 
        {
            _x = value;
            PointChanged(_x);
        }
    }

    public int YPoint
    {
        get
        {
            return _y;
        }
        set
        {
            _y = value;
            PointChanged(_y);
        }
    }

    public event Action<int> PointChanged;

    public void PrintPoints()
    {
        Console.WriteLine(" x: {0}, y: {1}", _x, _y);
    }

    public static void StaticMethod()
    {
        Console.WriteLine("Inside Static method");
    }
}

The above structure consists of different types of properties and events for the demo purpose. It includes private fields _x, _y, public fields x and y, static fields X and Y, public properties XPoint and YPoint, and PointChanged event. It also includes static and non-static methods. Notice that we raise the PointChanged event whenever XPoint or YPoint changes.

In the following code, we initialize the above Point struct with the new keyword as we initialize the class and also handle the PointChanged event:

Example: structure

class Program
{
    static void StructEventHandler(int point)
    {
        Console.WriteLine("Point changed to {0}", point);
    }

    static void Main(string[] args)
    {
        Point.StaticMethod();

        Point p = new Point();
        
        p.PointChanged += StructEventHandler;
        p.XPoint = 123;
        
        p.PrintPoints();
    }
}

Output:

Inside Static Method 
Point changed to 123 
X: 123, y: 0

Please note that if you want to use properties, methods or events, you MUST initialize the struct with the new keyword. The following will give a compile time error:

Example: structure

Point pto;

pto.XPoint = 100; // compile time error

Characteristics of Structure:

  • Structure can include constructors, constants, fields, methods, properties, indexers, operators, events & nested types.
  • Structure cannot include default constructor or destructor.
  • Structure can implement interfaces.
  • A structure cannot inherit another structure or class.
  • Structure members cannot be specified as abstract, virtual, or protected.
  • Structures must be initialized with new keyword in order to use it's properties, methods or events.

Difference between struct and class:

  • Class is reference type whereas struct is value type
  • Struct cannot declare a default constructor or destructor. However, it can have parametrized constructors.
  • Struct can be instasntiated without the new keyword. However, you won't be able to use any of its methods, events or properties if you do so.
  • Struct cannot be used as a base or cannot derive another struct or class.

Points to Remember :

  1. Structure is a value type and defined using struct keyword.
  2. Structure can be initialized with or without new keyword.
  3. Structure must be initialized with new keyword to use its' properties, methods and events.
posted Jan 23, 2017 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

Enum in C#:

In C#, enum is a value type data type. The enum is used to declare a list of named integer constants. It can be defined using the enum keyword directly inside a namespace, class, or structure. The enum is used to give a name to each constant so that the constant integer can be referred using its name.

Example: enum

enum WeekDays
{
    Monday = 0,
    Tuesday =1,
    Wednesday = 2,
    Thursday = 3,
    Friday = 4,
    Saturday =5,
    Sunday = 6
}

Console.WriteLine(WeekDays.Friday);
Console.WriteLine((int)WeekDays.Friday);

Output:

Friday 
4

By default, the first member of an enum has the value 0 and the value of each successive enum member is increased by 1. For example, in the following enumeration, Monday is 0, Tuesday is 1, Wednesday is 2 and so forth.

Example: enum

enum WeekDays
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

Console.WriteLine((int)WeekDays.Monday);
Console.WriteLine((int)WeekDays.Friday);

Output:


4

An explicit cast is necessary to convert from enum type to an integral type. For example, to get the int value from an enum:

Example: enum

int dayNum = (int)WeekDays.Friday;

Console.WriteLine(dayNum);

Output:

4

A change in the value of the first enum member will automatically assign incremental values to the other members sequentially. For example, changing the value of Monday to 10, will assign 11 to Tuesday, 12 to Wednesday, and so on:

Example: enum

enum WeekDays
{
    Monday = 10,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}
Console.WriteLine((int)WeekDays.Monday);
Console.WriteLine((int)WeekDays.Friday);

Output:

10 
14

The enum can includes named constants of numeric data type e.g. byte, sbyte, short, ushort, int, uint, long, or ulong.

enum cannot be used with string type.

Enum is mainly used to make code more readable by giving related constants a meaningful name. It also improves maintainability.

Enum methods:

Enum is an abstract class that includes static helper methods to work with enums.

Enum methodDescription
FormatConverts the specified value of enum type to the specified string format.
GetNameReturns the name of the constant of the specified value of specified enum.
GetNamesReturns an array of string name of all the constant of specified enum.
GetValuesReturns an array of the values of all the constants of specified enum.
object Parse(type, string)Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
bool TryParse(string, out TEnum)Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. The return value indicates whether the conversion succeeded.

Example: enum mehtods

enum WeekDays
{
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
}

Console.WriteLine(Enum.GetName(typeof(WeekDays), 4));

Console.WriteLine("WeekDays constant names:");

foreach (string str in Enum.GetNames(typeof(WeekDays)))
            Console.WriteLine(str);

Console.WriteLine("Enum.TryParse():");

WeekDays wdEnum;
Enum.TryParse<WeekDays>("1", out wdEnum);
Console.WriteLine(wdEnum);

Output:

Friday 
WeekDays constant names:
Monday 
Tuesday 
Wednesday 
Thursday
Friday
Saturday
Sunday 
Enum.TryParse(): 
Tuesday

Points to Remember :

  1. The enum is a set of named constant.
  2. The value of enum constants starts from 0. Enum can have value of any valid numeric type.
  3. String enum is not supported in C#.
  4. Use of enum makes code more readable and manageable.
READ MORE
...