Prashant Jadhav

Prashant Jadhav

  • NA
  • 38
  • 14.4k

instance field of struct

Jun 29 2014 9:54 AM
hello friends 
i was trying to initialize instance variable of an struct in my coding but i got error that i can not initialize instance member of  struct can any one tell me why cant we initialize instance variable of an struct on other hand we can initialize it in class why it is so.
this is the coding which i was trying hope some will illustrate it to me completely. thank you.
using System;
using System.Reflection;

namespace UserDefineConversionExpl
{
    struct LimitedInt
    {
        private int _theValue;
        private int MaxValue = 50;
        private int MinValue = 0;


        public int TheValuea
        {
            get
            {
                return _theValue;
            }
            set
            {
                if (value < MinValue)
                {
                    _theValue = 0;
                }
                else
                {
                    _theValue = value > MaxValue ? MaxValue : value;
                }
            }
        }
        public static implicit operator LimitedInt(int x)
        {
            LimitedInt li = new LimitedInt();
            li.TheValue = x;
            return li;
        }
        public static implicit operator int(LimitedInt li)
        {
            int x = li.TheValue;
            return x;
        }
        public static LimitedInt operator +(LimitedInt li, int x)
        {
            LimitedInt liSecond = new LimitedInt();
            liSecond.TheValue = li.TheValue + x;
            return liSecond;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            LimitedInt Li;
            Li = 8;
            Console.WriteLine(Li);
            Console.ReadLine();

        }
    }
}


Answers (3)