Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.

24 June 2012

structures in c#


In this article we will discuss about declaration of structures, assigning values to structure data members, reading values from structure data members, copying one structure to another structure, advantages of structures, nested structures and finally difference between a class and structure.
  • Structure is a logical group of items with different types.
  • Structure (also termed as structs) is a complex value type.  The data will be stored in stack memory.
  • Variable of struct types directly stores the data.
  • Derives from System.ValueType. 
  • You cannot define destructor for structs
  • Supports access modifiers, constructor, methods, indexers and properties.
  • Cannot initialize the data fields inside the struct definition.
Declaration a struct:
The general way of defining struct is
    [Attribute] [Access_Modifer] struct struct_Name[:interface1,interfaceN]
        {
            Datatype member1;
            Datatype memeber2;
            Body;
..
        }
Attributes – optional, which can have additional information.
Modifier – optional. Allowed modifiers are static,abstatct,override,new with combination of access modifiers(public,protected,private and internal).
Struct – mandatory..
Interfaces – are optional. Which is to implement number of interfaces.

Example:
struct Product
    {
        public int price;
        public string name;
        public int serialNO;
        int mfgYear; // by default modifier is Private
        //public int retialPrice=10;// Compile Error:says can not have instance field intilializers in structs 
  }
By default access modifier of struct data member is private. Even you explicitly give Private. Private members are not accessible outside the struct.
retialPrice data member is initialized to 10 within strcut definition. Which is compile time error. You “cannot have instance field initializers in structs”


Assigning values to struct data members:
//creating object of struct
Product objProduct = new Product();

            //Assigning values to struct members
            objProduct.name = "Apple";
            objProduct.price = 20;
            objProduct.serialNO = 1245;
//objProduct.mgfYear ---can not access private member

Reading struct data member values:
//Reading values from struct members
            Console.WriteLine("Product Name is:{0}",objProduct.name);
            Console.WriteLine("Product Price is:{0}", objProduct.price);
            Console.WriteLine("Product serial no is:{0}", objProduct.serialNO);

Copying struct:
We can copy on struct values to another struct by using
//copying struct to another sturct
Product objProductCopy;
objProductCopy = objProduct;

Example:
using System;

namespace Console_CSharp
{
    class StructUsage
    {
        public static void Main()
        {
            Product objProduct = new Product();
            //Assigning values to struct members
            objProduct.name = "Apple";
            objProduct.price = 20;
            objProduct.serialNO = 1245;
            //objProduct.mgfYear; //Can not access private members outside struct


            //Reading values from struct members
            Console.WriteLine("-----------------------------------------------");
            Console.WriteLine("Reading values from struct");
            Console.WriteLine("Product Name is:{0}", objProduct.name);
            Console.WriteLine("Product Price is:{0}", objProduct.price);
            Console.WriteLine("Product serial no is:{0}", objProduct.serialNO);


            //copying struct
            Product objProductCopy;
            objProductCopy = objProduct;
            //Reading values from copied struct members
            Console.WriteLine("-----------------------------------------------");
            Console.WriteLine("Reading values from copied struct");
            Console.WriteLine("Product Name is:{0}", objProductCopy.name);
            Console.WriteLine("Product Price is:{0}", objProductCopy.price);
            Console.WriteLine("Product serial no is:{0}", objProductCopy.serialNO);

            //creating object of struct with parameter consturctor
            Product objProduct1 = new Product(15, "Orange", 2011);
            //Assign value to struct Property
            objProduct1.ProfitPrice = 5;

            //Reading values from struct members
            Console.WriteLine("-----------------------------------------------");
            Console.WriteLine("Assigning and Reading values from parameter constructor");
            Console.WriteLine("Product Name is:{0}", objProduct1.name);
            Console.WriteLine("Product Price is:{0}", objProduct1.price);
            Console.WriteLine("Product Profit Price is:{0}", objProduct1.ProfitPrice);
            Console.WriteLine("Product serial no is:{0}", objProduct1.serialNO); //value will be 0 because no where it is assigned to value
            objProduct1.DisplayStrucPrivateMemeberVal();
            objProduct1.CalculateFinalPrice();
            //invoking Interface method which are implemented in struct
            objProduct1.Interface1Method();
            objProduct1.Interface2Method();
           
            Console.ReadKey();
                       
        }
    }
    struct Product:IProduct1,IProduct2
    {
        public int price;
        public string name;
        public int serialNO;
        int mfgYear; // by default modifier is Private
        //public int retialPrice=10;// Comiple Error:says can not have instance field intilializers in structs
        int _ProfitPrice;
                             
        //strcut with parameter constructor
        //public Product(int varPrice, string varName, int varMfgYear) -- gives
        //error need to assign all the data members. so use :this()
        public Product(int varPrice, string varName, int varMfgYear):this()
        {
            this.price = varPrice;
            this.name = varName;
            this.mfgYear = varMfgYear;
        }
        //struct with Property
        public int ProfitPrice
        {
            get
            {
                return _ProfitPrice;
            }
            set
            {
                _ProfitPrice = value;
            }
        }
        public void CalculateFinalPrice()
        {
            Console.WriteLine("Final selling price of product is:{0}", this.price + this.ProfitPrice);
        }
        public void DisplayStrucPrivateMemeberVal()
        {
            Console.WriteLine("Private data member mfgYear value is :{0}", mfgYear);
        }
       
        //Implementation of Interfaces
        #region IProduct1 Members

        public void Interface1Method()
        {
            Console.WriteLine("Method from IProduct1 Interface");           
        }
        #endregion

     
        #region IProduct2 Members

        public void Interface2Method()
        {
            Console.WriteLine("Method from IProduct2 Interface");
        }

        #endregion
    }

    //interfaces
    interface IProduct1
    {
        void Interface1Method();
    }
    interface IProduct2
    {
        void Interface2Method();
    }
}

Output:
Fig: struct example output


Advantages of structs:
  • Creation is faster than heap-allocated types
  • Instantly and automatically deallocated once they go out of scope
  • Easy to type value type variable on the stack.

Nested Structs:
We can have one struct inside another struct. Nesting of struct can be done in 2 ways
  1. Nesting struct - Nesting whole declaration of struct into other struct
  2. Member struct - Use the struct as member variable in another struct.
we will see the examples of nesting struct and member struct below.
 
1.       Nesting struct:
Syntax:
    struct Parent
    {
        // public member variables  
    }
    struct Child
    {
        public Parent P;
        // public member variables  
    }

Example:
   class StructNestedUsage
    {
        public static void Main()
        {
            ProductInfoNestedStruct varProduct;
            varProduct.name = "Pen";
            varProduct.serialNO = 12345;

            //Nested struct(Price) variable
            ProductInfoNestedStruct.Price varPrice;
            varPrice.ActualPrice = 20;
            varPrice.DiscoutPrice = 15;
          
        }
      
    }
    struct ProductInfoNestedStruct

    {
        public string name;
        public int serialNO;
        public struct Price // if access specifier is not public. otherewise It will take as Privte in another class
        {
            public int ActualPrice;
            public int DiscoutPrice;
        }

    }
     
Note: Price is a struct variable inside a struct. Show it should specify access modifier as public otherwise you can not access ProductInfo.Price outside struct.

2.       Member struct
Syntax:
    struct Parent
    {
        // public member variables  
        public struct Child
        {
            // public member variables  
        }
    }
Example:
class StructNestedUsage
    {
        public static void Main()
        {
            //accessing Member struct
            Price varPrice1;
            varPrice1.ActualPrice = 5;
            varPrice1.DiscoutPrice = 3;

            varPrice1.varProductInfoMemberStruct.name = "Pencil";
            varPrice1.varProductInfoMemberStruct.serialNO = 86;
        }
      
    }
   
    //member struct
    struct ProductInfoMemberStruct
    {
        public string name;
        public int serialNO;
    }
    struct Price
    {
       //struct declared as member variable
        public ProductInfoMemberStruct varProductInfoMemberStruct; //should be explicitly specify as Public
        public int ActualPrice;
        public int DiscoutPrice;
    }

Note: ProductInfoMemberStruct is a member variable inside a struct. Show it should specify access modifier as public otherwise you can not access outside struct.

Class vs structures:
Structure
Class
Value type
Reference type
After instantiation memory will be created on stack.
After instantiation memory will be created on heap
Does not Support inheritance. But can implement interfaces
Supports inheritance and implementation of interfaces
Does not support default( parameter less )constructor
It supports default(parameter less) constructor
Cannot define destructor
Can have destructor
Does not permit initialization of instance fields with in definition
Permits initialization of instance fields with in definition
On assignment values data is copied
On assignment copies the reference
Memory deallocation done when they go out of scope
Memory deallocation handled by garbage collector.



0 Comments:

Post a Comment