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»