Friday, September 13, 2019

C# Struct


Struct type is value type which inherits from object type and struct keyword is used to define the Struct type in C#.

Define the Struct :

Here is an example of srtuct type – Point which has two properties X & Y co-ordinate

       struct point
        {
            public int x;
            public int y;
        }


Define a constructor of Struct:

We can define the constructor of Struct type to initialize the struct type’s variables

struct point
        {
            public int x;
            public int y;

            public point(int _x , int _y)
            {
                x = _x;
                y = _y;
            }
        }

a struct cannot declare a parameterless constructor .

Define a method of Struct:

We can define a method or function in struct type and there are two Distance () methods to calculate distance between two given points

     struct point
        {
            public int x;
            public int y;

            public point(int _x , int _y)
            {
                x = _x;
                y = _y;
            }

            public double Distance(point p1, point p2)
            {
                return Math.Sqrt(((p1.x - p2.x) * (p1.x - p2.x)) + ((p1.y - p2.y) * (p1.y - p2.y)));
            }

            public double Distance(point p1)
            {
                return Math.Sqrt(((this.x - p1.x) * (this.x - p1.x)) + ((this.y - p1.y) * (this.y - p1.y)));
            }
        }


Instantiate the object of Struct:

new keyword is used to instantiate the object of struct and it calls constructor to set the initial value of struct

point p1 = new point(1,2)

But without new keyword, we can create instance of struct with default value.

point p1;

both struct properties p1.x and p1.y have default unassigned value

Instantiate the Array of Struct type:

Here is an examples of array of struct type

point [] Points = new point[] { new point(2, 3), new point(12, 30 ), new point(40, 50 ) };

Difference between Structs and Classes:

Struct
Class
Struct cannot inherit another struct
Classes can inherit from another class
Struct cannot  be de-initialized
Classes can be de-initialized,
Struct is value type
Class is reference type
Struct cannot have parameterless constructor
Class can have parameterless constructor



No comments:

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...