C# Programming - Classes and Objects - Discussion
Discussion Forum : Classes and Objects - General Questions (Q.No. 6)
6.
Which of the following will be the correct output for the C#.NET program given below?
namespace IndiabixConsoleApplication
{
class Sample
{
int i;
Single j;
public void SetData(int i, Single j)
{
i = i;
j = j;
}
public void Display()
{
Console.WriteLine(i + " " + j);
}
}
class MyProgram
{
static void Main(string[ ] args)
{
Sample s1 = new Sample();
s1.SetData(10, 5.4f);
s1.Display();
}
}
}
Discussion:
28 comments Page 3 of 3.
Swati mahajan said:
1 decade ago
Answer is 0 0 because not added this in SetData();.
Penchala Naidu said:
1 decade ago
Whenever parameters names and instance variables name are same we need to make use of "this" keyword in the method body to refer to instance variables.
Muthu (VMK) said:
1 decade ago
@ Durg, Well Said.
Until you explain about this Keyword no beginner could understand.
Until you explain about this Keyword no beginner could understand.
Durg said:
1 decade ago
In this, as s1 is created, default constructor initialize field variable i, j by default value.
i.e, i = 0; j = 0;
-------------
When we are calling s1.SetData(10, 5.4f) , we assign value to local variable i, j; which we define in formal argument ( not field variable )
That's why, compiler generate warning ---
" value is assign to same variable".
-------------
If you want to initialize field variable then
1. use 'this' keyword ,like this.i and this.j
2. use different name for parameter variable.
i.e, i = 0; j = 0;
-------------
When we are calling s1.SetData(10, 5.4f) , we assign value to local variable i, j; which we define in formal argument ( not field variable )
That's why, compiler generate warning ---
" value is assign to same variable".
-------------
If you want to initialize field variable then
1. use 'this' keyword ,like this.i and this.j
2. use different name for parameter variable.
Akmal said:
1 decade ago
@Rajeev...
why s1.Display() call default constructor since i and j in same object,s1?
why s1.Display() call default constructor since i and j in same object,s1?
Ranjana said:
1 decade ago
Here we did not use the this keyword so that it displayed null values.
Narmadha said:
1 decade ago
Here in Line s1.Setdata(10,5.4f);
So Here we called only floating point number, so its displayed 0,0 .
So Here we called only floating point number, so its displayed 0,0 .
Rajeev said:
1 decade ago
It is because the s1.SetData(10, 5.4f); will set the values if i, j but in line s1.Display(); function will call default constructor and default values assigned to i,j (0,0) . that is why it will print 0 0
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers