Friday, February 24, 2012

Structures in .NET

As we discussed in previous post, enumerations and structures are two complex types that are value types. Structures allow you encapsulate certain data elements similar to a class, except that structures are value types while classes are reference types.

Structures are very similar to classes with few differences.
  • Unlike classes, structures cannot inherit from other structures or a class, although they can implement interfaces.
    • Since they cannot inherit from other structures, an structure cannot be a base structure, which means structure members cannot be declared as "Protected".
  • Similar to classes, structures can have constructors, properties, methods etc.
  • Unlike classes, you cannot declare a parameterless constructor in a structure, although you can declare overloaded constructors with parameters. Strucutres always have a default constructor.
  • Unlike classes, you can instantiate an structure without using "new" operator.
Structures are suitable when you want to implement lightweight objects such as a point or color or a rectangle etc. 

Let's see an example in action...

    using System;
    struct StructExample
    {
        private int _width;
        private int _height;
   
        public int Width
        {
            get { return _width;}
            set {_width = value;}
         }

       public int Height
      {
           get { return _height;}
           set {_height = value;}
      }
   }


Let's use this structure

    Using System;
    class TestStructure
    {
       static void Main()
       {
             StructExample example1 = new StructExample();
             example1.Width  =1;
             example2.Height = 3;
             Console.WriteLine(example1.Width + ' ' + example1.Height);
             Console.Read();
        }
    }

As I mentioned previously, you should only use structures for lightweight objects because they are value types and are stored on a stack. Also, since they are not reference type, you are directly dealing with the structure and not with a reference, like you would with a class.

Thank you.








No comments:

Post a Comment