Donate

Structures Example In C#.NET

Good evening team,

Before migrating to .NET, i used to code a lot in C++/C.. One of the topics in data structures was structures .C# also has struct in its arsenal.A structure is similar to a class, but is a value type, rather than a reference type. Structures are declared using the keyword struct and are syntactically similar to classes. Here is the general form of a struct.
struct name : interfaces
{
   // member declarations
}
The name of the structure is specified by name.Structures cannot inherit other structures or classes, or be used as a base for other structures or classes. (Of course, like all C# types, structures do inherit object.) However, a structure can implement one or more interfaces. These are specified after the structure name using a comma-separated list. Like classes, structure members include methods, fields, indexers, properties, operator methods, and events. Structures can also define constructors, but not destructors. However, you cannot define a default (parameterless) constructor for a structure. The reason for this is that a default constructor is automatically defined for all structures, and this default constructor can’t be changed. The default constructor initializes the fields of a structure to their default values. Since structures do not support inheritance, structure members cannot be specified as abstract, virtual, or protected. (FROM: C# COMPLETE REFERENCE)So, to give an example, here is a struct that computes the area of a rectangle.
public struct MyStruct {
  public int height;
  public int width;
  public MyStruct(int h, int w) {
    this.height = h;
    this.width = w;
  }
  public override string ToString() {
    return (width * height).ToString();
  }
}
//And here is the test program:  
static void Main(string[] args) {
    MyStruct s;
    s.width = 5;
    s.height = 5;
    //declare s1 similar to instantiation of objects  
    MyStruct s1 = new MyStruct(9, 7);
    Console.WriteLine("Area of first rectangle is: {0} second  
      is: {
        1
      }
      ", s.ToString(),s1.ToString());  
      //array of structs  
      MyStruct[] s2 = new MyStruct[3]; s2[0].height = 8; s2[0].width = 4; s2[1].height = 10; s2[1].width = 10; s2[2].height = 12; s2[2].width = 2; Console.WriteLine("\n"); foreach(var @struct in s2) {
        Console.WriteLine("Area of the three rectangle are: {0}",
          @struct.ToString());
      }
    }
As you can see from the test program, you can declare a struct object w/o specifying a new keyword. You could also declare a struct object using the new keyword, provided that you supply values to it's constructor. The third code also let's you create an array of structures.

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Pass GUID As Parameter To Action Using ASP.NET MVC ContribGrid