C# Programming - Structures - Discussion

Discussion :: Structures - General Questions (Q.No.3)

3. 

Which of the following will be the correct output for the C#.NET program given below?

namespace IndiabixConsoleApplication
{ 
    struct Sample
    {
        public int i;
    }
    class MyProgram
    { 
        static void Main()
        {
            Sample x = new Sample(); 
            x.i = 10; 
            fun(x); 
            Console.Write(x.i + " ");
        }
        static void fun(Sample y)
        {
            y.i = 20; 
            Console.Write(y.i + " ");
        } 
    } 
}

[A]. 10 20
[B]. 10 10
[C]. 20 10
[D]. 20 20
[E]. None of the above

Answer: Option C

Explanation:

No answer description available for this question.

Ashok said: (Mar 2, 2012)  
Please can any one explain the above program.

Prabha said: (May 7, 2012)  
Structure is of value type, so its value is not changed.

Lokesh said: (Jul 17, 2012)  
Structures are value types and stored on stack not on heaps.

Abhishek Singh said: (Jul 10, 2013)  
As Structures are value type. They hold different memory location for each instance (struct in this case is value type ). Hence x.i would point to one mem location whereas for y.i to another.

Hence fun(x) would call the fun method. But again y.i is assigned 20. Hence a Console would give 20 first and then control would be transferred to main() again and the next statement for x.i ( print ) would give 10.

Hence the output : 20 10.

Priyanka R said: (Sep 15, 2014)  
Structure is not matter this place. That method was call by value. So, the value not changed in memory structure.

Pradeep said: (Oct 7, 2014)  
Does structures have constructor. I have no idea. Does anyone?

Sharan said: (Mar 4, 2015)  
Structures have default constructor.

Brijbhan said: (Mar 17, 2015)  
X and Y are totally different so answer is 20, 10.

Mohammad Adil said: (May 27, 2016)  
In general, the changes in the function prototype with parameters do not reflect on arguments of the calling function (because the types of variable here is value type).

If we use ref keyword with parameters and arguments then the changes on the parameter are directly reflected on arguments and they are become reference type and allocate same memory address.

Saikat said: (Aug 9, 2016)  
Structures contain defined constructor.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.