C# Programming - Structures - Discussion

Discussion :: 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); 
        } 
    } 
}

[A]. 9 9
[B]. 9 5
[C]. 5 5
[D]. 5 9
[E]. None of the above

Answer: Option B

Explanation:

No answer description available for this question.

Bhupi said: (Sep 23, 2011)  
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: (Jul 24, 2015)  
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: (Feb 18, 2019)  
@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;

}

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.