C# Programming - Structures - Discussion

Discussion Forum : 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 + " ");
        } 
    } 
}
10 20
10 10
20 10
20 20
None of the above
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
10 comments Page 1 of 1.

Abhishek Singh said:   1 decade ago
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.
(1)

ASHOK said:   1 decade ago
Please can any one explain the above program.

Prabha said:   1 decade ago
Structure is of value type, so its value is not changed.

Lokesh said:   1 decade ago
Structures are value types and stored on stack not on heaps.

Priyanka R said:   1 decade ago
Structure is not matter this place. That method was call by value. So, the value not changed in memory structure.

Pradeep said:   1 decade ago
Does structures have constructor. I have no idea. Does anyone?

Sharan said:   1 decade ago
Structures have default constructor.

Brijbhan said:   1 decade ago
X and Y are totally different so answer is 20, 10.

Mohammad Adil said:   9 years ago
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:   9 years ago
Structures contain defined constructor.

Post your comments here:

Your comments will be displayed after verification.