Question #38393

In the written examination conducted by WebSoft Solutions Pvt. Ltd., candidates are given certain
advanced C# codes. They are asked to find the errors in the code (if any) and predict the output of
the code. You are one of the candidates appearing at the interview. Optimize the code, find out the
errors (if any), and predict the output of the following code snippet: [10 Marks]
using System;
class Student
{
private string name = "Marcus Trott";
private double marks = 65.0;
public void DispName()
{
System.Console.WriteLine("Name: ",; name);
}
public void DispMarks()
{
System.Console.WriteLine("Marks: ", marks);
}
}
class MainClass
{
static void Main()
{
Student s= new Student();
string n = s.DispName();
double m= s.marks;
}
}

Expert's answer

Answer on Question#38393 - Programming – C#

Original code has several mistakes:


using System;
class Student
{
private string name = "Marcus Trott";
private double marks = 65.0;
public void DispName()
{
System.Console.WriteLine("Name: ", name); // «;» symbol is waste also wrong syntax
}
public void DispMarks()
{
System.Console.WriteLine("Marks: ", marks); // wrong syntax for this method
}
}
class MainClass
{
static void Main()
{
Student s = new Student();
string n = s.DispName(); // error, this method returns void, it can't be assigned to variable
double m = s.marks; // this field is closed for the entry point
}
}


Fixed code:


using System;
class Student
{
// in C# default access modificator is «private», so it is better not to rewrite it
string name = "Marcus Trott";
double marks = 65.0;
public string DispName() // this method should return a string for assigning
{
Console.WriteLine("Name: " + name); // bugs fixed
return name; // returning string value
}
public double DispMarks()
{
// no System. Console because we conduct this namespace in the first line of the program
Console.WriteLine("Marks: " + marks);
return marks;
}
}
class MainClass
{
static void Main()
{
Student s = new Student();
string n = s.DispName();
double m = s.DispMarks(); // showing closed(private) field
}
}


Out will be:

Name: Marcus Trott

Marks: 65

, also variables «n» «m» will contain corresponding values - «Marcus Trott» and «65.00000»

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS