Wednesday, April 24, 2013

struct in C# .NET

Structure in C sharp Dot net

1. How to Use Struct in C sharp

2.Structure Declaration

3.Difference between Struct and Classes


==>> STRUCT is an encapsulated entity.

==>> STRUCT does not use complete OOPS concept but are used to define a data types.

==>>STRUCT is a value type.

==>>All the members of a STRUCT has to be initialized , as it is a value type.

==>> STRUCT is a simple user defined data type.

==>>STRUCT is a lightweight alternative to class.

==>>Similar to CLASS , STRUCT have also behaviors and attributes.

==>>As STRUCT is a value type , STRUCT contains their value directly so their object or instance is stored in a   

     stack.
==>> STRUCT supports

         * ACCESS MODIFIERS
         * CONSTRUCTORS
         *INDEXERS
         *METHODS
         *FIELDS
         *OPERATORS
         *PROPERTIES

How can we define a sturct?


public struct Student
        {
            int id;
            int zipcode;
            double salary;
        }

Note: struct members may not be declared protected.

Structs are simple to use and can prove to be useful at times. Just keep in mind that they're created on the stack and that you're not dealing with references to them but dealing directly with them. Whenever you have a need for a type that will be used often and is mostly just a piece of data, structs might be a good option.

Practical demonstration of struct


using System;

namespace example_struct
{
    class Program
    {
        public struct Student
        {
            int id;
            int zipcode;
            double salary;

            // all the members of the struct has to be initialized in this way
            public Student(int id, int zipcode, double salary)
            {
                this.id = id;
                this.zipcode = zipcode;
                this.salary = salary;
            }

            // all the members of the struct has to be initialized either in this way
            public Student(int id, int zipcode)
            {
                this.id = id;
                this.zipcode = zipcode;
                this.salary = 3400.00;
            }

            // if you left any member of a struct uninitialzed it will give error
            // code below will give error because the zipcode and salary field is left uninitialzed

            //public Student(int id)
            //{
            //    this.id = id;
            //}

            // struct can also have copy constructor but have to be fully initialzed
            public Student(Student x)
            {
                this.id = x.id;
                this.zipcode = x.zipcode;
                this.salary = x.salary;
            }

            public void DisplayValues()
            {
                Console.WriteLine("ID: " + this.id.ToString());
                Console.WriteLine("Zipcode : " + this.zipcode.ToString());
                Console.WriteLine("Salary : " + this.salary.ToString());
            }
        }

        static void Main(string[] args)
        {
            Student stu = new Student(12, 201301, 4560.00);
            Student stu1 = new Student(stu);

            stu.DisplayValues();

            Console.WriteLine("Copy constructor values");
            stu1.DisplayValues();

            Console.ReadLine();
        }
    }
}

Some points about structs 

  • Struct is used to improve the performance and clarity of code.
  • Struct uses fewer resources in memory than class.
  • When we have small and frequent use of some work use structs over classes.
  • Performance can suffer when using structures in situations where reference types are expected due to boxing and unboxing.
  • You should pass structs to method as ref parameters in order to avoid the performance loss associated with copying data.
  • Structs reside on the stack, so we should keep them small.
  • Structs can't be inherited and we can say they are sealed.
  • Structure implicitly inherits from System.ValueType.
  • The default constructor of a structure initializes each field to a default value. You cannot replace the default constructor of a structure.
  • You can't define destructor for structs
  • Structs can be inherited from an interface?
 Practical program showing that struct and inherit from an interface:

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

namespace example_struct_using_interface
{
    class Program
    {

        public interface aa
        {
            // no access specifier is given in interface methods (by defualt they are public)

            double Increment();
            void DisplayValues();
        }

        public struct Student : aa
        {
            int id;
            int zipcode;
            double salary;

            public Student(int id, int zipcode, double salary)
            {
                this.id = id;
                this.zipcode = zipcode;
                this.salary = salary;
            }

            public void DisplayValues()
            {
                Console.WriteLine("ID: " + this.id.ToString());
                Console.WriteLine("Zipcode : " + this.zipcode.ToString());
                Console.WriteLine("Salary : " + this.salary.ToString());
            }

            public double Increment()
            {
                return(this.salary += 1000.00);
            }
        }

        static void Main(string[] args)
        {
            Student stu = new Student(12, 201301, 4560.00);
            stu.DisplayValues();
            Console.WriteLine("Salary after increment is {0}", stu.Increment());
            Console.ReadLine();
        }
    }
}

Structs and inheritance


Structs don't provide inheritance. It is not possible to inherit from a struct and a struct can't derive from any class.

Once exception that all type in C# is derive from the class System.Object, so structs also have the access to the methods etc., of System.Object.

Note: Inheritance is indirect: Structs derive from System.ValueType, which in turns derive from System.Object.ValueType adds no new method of its own, but provides overrides of some the Object methods that are more appropriate to value types.

Difference between structs and classes


structs
classes
  • structs are value type
  • classes are reference type
  • structs are stored in stack or a inline
  • classes are stored on managed heap
  • structs doesn't support inheritance
  • classes support inheritance
  • But handing of constructor is different in structs. The complier supplies a default no-parameter constructor, which your are not permitted to replace
  • Constructors are fully supported in classes

No comments:

Post a Comment