Structure in c#

namespace CSharpBasics
{

    //Cannot be declare sealed/abstract
    /*
* A structure or struct can contain only fields, methods, Etc., 
* In struct we can't initialize the variable whereas in class it can be possible 
* It must be initialized either through function or using object 
* Fields can't be given initial values at that time of creation. 
* struct can't have a PARAMETER-LESS constructor. 
* struct can't support the concept of inheritance 
* We can derive a structure from an interface 
* We can't inherit from sealed class 
* A structure could not inherit from a class, the reverse is also true 
* You can't declare a struct as sealed, because by default it is sealed 
* A structure declare as abstract can't be used as a base class, i.e., be used in a derivation 
* No destructor for struct 
* struct are created on the stack and die when we reach the closing brace 
    */
    struct Structure
    {
        //Structure cannot have PARAMETER-LESS construtors
        //public Structure()  
        //{ }

        // DEFAULT is PRIVATE
        int j; //Field must be fully assigned before control leaves the constructor	


        //Structs cannot contain explicit parameterless constructors
        
        //Struct are assumpted to be lightweight. According to it,
        //all struct have compiler-defined default constructor(with
        //no parameters), that assigns all values to zero value(0 to
        //int,null to ref,e.t.c.). This constuctor is more
        //effective, than putting zero one-one at other constructor.
        //Use Static constructor if you want to initialize some thing before hand.
        
        //public Structure() { }

        public Structure(int i)
        {
            j = i; //As structure require us to assign a value to field in constructor
        }

        public string s_method1()
        {
            return "struct1";
        }

        public override string ToString()
        {
            return string.Format("value of i is {0}", j.ToString());
        }
    }

    struct Structure1 
    {
        Structure s; //can not have  = new Structure(1); statement here as we cannot define the feilds here (either in function or constructors else they will take the default value.
        string s_method2()
        {
            s = new Structure(1);
            return s.s_method1();
        }
 
    }
}

Add Comments :

Login

Register