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 + " ");
}
}
}
Discussion:
10 comments Page 1 of 1.
Saikat said:
9 years ago
Structures contain defined constructor.
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.
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.
Brijbhan said:
1 decade ago
X and Y are totally different so answer is 20, 10.
Sharan said:
1 decade ago
Structures have default constructor.
Pradeep said:
1 decade ago
Does structures have constructor. I have no idea. Does anyone?
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.
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.
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)
Lokesh said:
1 decade ago
Structures are value types and stored on stack not on heaps.
Prabha said:
1 decade ago
Structure is of value type, so its value is not changed.
ASHOK said:
1 decade ago
Please can any one explain the above program.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers