Thursday, March 28, 2013

How to create structures in C# ? [keyword: struct]


Structures are basically user defined types. Structures differ from classes
as they do not contain data directly unlike 'Classes'.
While the functionality is similar, structures are usually more efficient as compared to classes.

A structure is preferred over a class if, a type will perform better as value type than as value type.

A structure must meet following criteria:-
1.It should logically represent a single value.
2.The size of an instance should not be more than 16 bytes.
3.It need not be changed frequently after creation.
4.It is not cast to a reference type.(i.e converted to another type or typecast)

This is an example of employee structure.

using System;
using System.Collections.Generic;
using System.Text;

namespace Structures
{
    class Program
    {
        static void Main(string[ ] args)
        {
            Employee E = new Employee("Shantanu", "Shirpure", 666);
            Console.WriteLine(E.ToString());
            Console.ReadLine();
        }

        struct Employee
        {
            public string firstName;
            public string lastName;
            public int id;

            public Employee(string firstName, string lastName, int id) // this is a constructor.
            {
               //   firstName = firstName;
                this.firstName = firstName;
                // Here string firstName of struct Employee has scope
                //all through the methods hence to distinguish from parameters invoke this method.
                this.lastName = lastName;
                this.id = id;
            }

            public override string ToString() // this is a method.
            //override is a key word used to duplicate the systems method ToString with our own method
            //this is called as polymorphism
            {
                return firstName + " " + lastName + ", ID " + id;
            }
        }
    }
}

No comments: