-2
namespace learning
{
    class Gradebook
    {
        public Gradebook()
        {
            grades = new List<float>();  
        }
        public void AddGrade(float grade)
        {
            grades.Add(grade);
        }
        public Gradestatistic compute_statistics()
        {
            Gradestatistic stats = new Gradestatistic();
            float sum = 0f;
            foreach (float grade in grades)
            {
                sum = sum + grade;

            }
            stats.average_grade = sum / grades.Count;
            return stats;
        }
        List<float> grades;


    }
}

I am using two custom classes Gradebook and Gradestatistic respectively , my object of class gradestatistic is stats , average_grade is the member of class gradestatistic, when i built this program it shows error on stats.average_grade = sum / grades.Count; which is can not implicitly convert type float to learning.gradestatistic . learning is my project name. the code of gradestatistic class is

class Gradestatistic
    {

        public Gradestatistic highest_grade;
        public Gradestatistic lowestgrade;
        public Gradestatistic average_grade;
    }

my program.cs code is

class Program
    {
        static void Main(string[] args)
        {
            Gradebook book = new Gradebook();
            book.AddGrade(91);
            book.AddGrade(89.9f);
            Gradestatistic stats = book.compute_statistics();

        }
    }
faizan
  • 109
  • 7

2 Answers2

0

The code is failing to compile because you are trying to assign a value of type float to a field of type Gradestatistic. C# is a type-safe language which means you can't assign one type to another unless there is a conversion defined from one to the other.

Looking at your code it seems your Gradestatistic should have float type of fields, not Gradestatistic. Changing them to float will solve the issue:

class Gradestatistic
{
    public float highest_grade;
    public float lowestgrade;
    public float average_grade;
}

Although this will solve your problem, exposing a class fields like that is considered a bad programming practice. You can read more on that in the below questions:

You should prefer automatic properties over public fields.

Community
  • 1
  • 1
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • yeah the problem is solved , thanks for your time , and I'll surely operate your suggestion of using properties over public field :) – faizan Mar 24 '17 at 19:13
0

You should change the Gradestatistic class to:

class Gradestatistic
{
    public float highest_grade { get; set; }
    public float lowestgrade { get; set; }
    public float average_grade { get; set; }
}