Rick Walker
Rick Walker

Reputation: 97

Setting read-only property from a method

I have a simple problem, but I'm stuck as a newbie.

My SetGrade method takes a float parameter and I would like it to return a char and then set that value to the Grade property.

I'm not doing something correctly.

public Class Student {
    private char grade;

    public char Grade { get { return grade; } }

    public char SetGrade(float score) {
        char Mgrade;
        if(score >= 90.0) {
            return Mgrade = 'A';
        }
        return Mgrade = 'F';
     }
}

Upvotes: 1

Views: 260

Answers (3)

Eric Lippert
Eric Lippert

Reputation: 659964

There are numerous problems with this code but they might not be what you think they are.

First off, Public is wrong; C# requires public.

Second, the use of the local Mgrade is strange and unnecessary, but interestingly enough not actually wrong; it is legal to do an assignment and a return in one step like that. But in this case you do not need to; just return 'A'; without the local assignment.

Third, the method is misnamed because it does not set the Grade property. If you intend it to set the grade then it should be void returning:

public void SetGrade(float score)
{
   if(score >= 90.0)
   {
      this.grade = 'A';
   }
   this.grade = 'F';
} 

If instead the method is intended to be a conversion from floats to chars then it should be static:

public static char ScoreToGrade(float score)
{
   if(score >= 90.0)
   {
      return 'A';
   }
   return 'F';
} 

Frankly, I'd be inclined to do both:

public void SetGrade(float score)
{
  this.grade = ScoreToGrade(score);
} 

There, now you've got the best of both worlds.

Fourth, this is just a stylistic point; you might consider:

  public char Grade { get; private set; }

the compiler will generate an "invisible" backing field for you, so you don't have to manage it yourself. This syntax means that Grade can be read from anywhere and written to from within this class.

Upvotes: 15

Claudio Redi
Claudio Redi

Reputation: 68400

No need to assign your character to an intermediate char variable. Just return correct character like this.

public char SetGrade(float score)
{
   if(score >= 90.0)
   {
      return 'A';
   }
   return 'F';
}

Upvotes: 6

Oded
Oded

Reputation: 498914

Your syntax is a bit off:

  public char SetGrade(float score)
  {
     if(score >= 90.0)
     {
       return 'A';
     }
     return 'F';
  }

No need for the Mgrade variable and you should simply return the character wanted, instead of an assignment and return.

Upvotes: 2

Related Questions