C# Programming - Structures - Discussion

Discussion Forum : Structures - General Questions (Q.No. 17)
17.
Which of the following will be the correct output for the program given below?
namespace IndiabixConsoleApplication
{ 
    struct Sample
    {
        public int i;
    }
    class MyProgram
    { 
        static void Main(string[] args)
        {
            Sample x = new Sample();
            Sample y;
            x.i = 9;
            y = x;
            y.i = 5;
            Console.WriteLine(x.i + " " + y.i); 
        } 
    } 
}
9 9
9 5
5 5
5 9
None of the above
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
3 comments Page 1 of 1.

Bhupi said:   1 decade ago
Though the object is copied as it is but in the next line for the second object the value is changed so it will be a change in value for the object y's variable i.

Sark said:   1 decade ago
Because struct is a value type, when a instance assigned to another, all the elements will be copied to another location in stack, but vice versa when using class object.

See the example:

public class Sample
{
public int i;
}
public class MyProgram
{
public static void Main(string[] args)
{
Sample x = new Sample();
Sample y;
x.i = 9;
y = x;
y.i = 5;
Console.WriteLine(x.i + " " + y.i);
}
}


Result.

5 5.

Oli said:   7 years ago
@Saks.

The answer is right. It is a struct and passed as a copy. not a reference type.

See sample code

struct Sample
{
int i;
};
int _tmain(int argc, _TCHAR* argv[])
{


struct Sample x;
struct Sample y;

x.i = 9;
y = x;
y.i = 5;

cout << x.i + " " + y.i << endl;

return 0;

}
(1)

Post your comments here:

Your comments will be displayed after verification.