Register Now

Login

Lost Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

What will be the output of the following C# code?
class sample
{
public int i;
public int[] arr = new int[10];
public void fun(int i, int val)
{
arr[i] = val;
}
}
class Program
{
static void Main(string[] args)
{
sample s = new sample();
s.i = 10;
sample.fun(1, 5);
s.fun(1, 5);
Console.ReadLine();
}
}

What will be the output of the following C# code?
class sample
{
public int i;
public int[] arr = new int[10];
public void fun(int i, int val)
{
arr[i] = val;
}
}
class Program
{
static void Main(string[] args)
{
sample s = new sample();
s.i = 10;
sample.fun(1, 5);
s.fun(1, 5);
Console.ReadLine();
}
}
a) sample.fun(1, 5) will not work correctly
b) s.i = 10 cannot work as i is ‘public’
c) sample.fun(1, 5) will set value as 5 in arr[1]
d) s.fun(1, 5) will work correctly

Answer: a
Explanation: An Object reference is required for non static field, method or property. i.e
sample s = new sample();
s.i = 10;
sample.fun(1, 5);
sample.fun(1, 5);
Console.ReadLine();

Join The Discussion