C# Programming - Functions and Subroutines - Discussion
Discussion Forum : Functions and Subroutines - General Questions (Q.No. 8)
8.
Which of the following statements are correct?
- C# allows a function to have arguments with default values.
- C# allows a function to have variable number of arguments.
- Omitting the return value type in method definition results into an exception.
- Redefining a method parameter in the method's body causes an exception.
- params is used to specify the syntax for a function with variable number of arguments.
Discussion:
7 comments Page 1 of 1.
Dexter Williams said:
8 years ago
@Sunshine.
Option 2 is true due to the params data type.
See the following code:
public class Program
{
public static void Main(string[] args)
{
int i, j;
Program obj = new Program();
i = obj.sumNumbers(10);
j = obj.sumNumbers(10, "desk", 34, 50);
Console.WriteLine("{0}, {1}", i, j);
}
public int sumNumbers(params object[] list)
{
int newSum = 0;
for (int i = 0; i < list.Length; i++)
{
if (list[i].GetType() == typeof(int))
newSum += (int) list[i];
}
return newSum;
}
}
Output: 10, 94.
Option 2 is true due to the params data type.
See the following code:
public class Program
{
public static void Main(string[] args)
{
int i, j;
Program obj = new Program();
i = obj.sumNumbers(10);
j = obj.sumNumbers(10, "desk", 34, 50);
Console.WriteLine("{0}, {1}", i, j);
}
public int sumNumbers(params object[] list)
{
int newSum = 0;
for (int i = 0; i < list.Length; i++)
{
if (list[i].GetType() == typeof(int))
newSum += (int) list[i];
}
return newSum;
}
}
Output: 10, 94.
Ranjan said:
1 decade ago
Option 1 is also right.
See the following code:
class Program
{
static void Main(string[] args)
{
int i, j;
Program obj = new Program();
int s = obj.sum(10);
Console.WriteLine("{0}", s);
Console.ReadLine();
}
public int sum( int i,int j=10)
{
return i + j;
}
}
See the following code:
class Program
{
static void Main(string[] args)
{
int i, j;
Program obj = new Program();
int s = obj.sum(10);
Console.WriteLine("{0}", s);
Console.ReadLine();
}
public int sum( int i,int j=10)
{
return i + j;
}
}
Gopesh said:
1 decade ago
@Soumya.
You can't write.
int i;
function (i) ;
//Since I have a default value but you can't pass it without initializing.
You can't write.
int i;
function (i) ;
//Since I have a default value but you can't pass it without initializing.
Sunshine said:
9 years ago
Can anyone explain the option 2? I didn't understand.
Soumya said:
1 decade ago
What about option 1 ?
SergeyD said:
6 years ago
1, 2, 5 are correct.
Bhagwan said:
7 years ago
Why not option A?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers