c# - Setting read-only property from a method -
i have simple problem, i'm stuck newbie.
my setgrade
method takes float parameter , return char , set value grade property.
i'm not doing correctly.
public class student { private char grade; public char grade { { return grade; } } public char setgrade(float score) { char mgrade; if(score >= 90.0) { return mgrade = 'a'; } return mgrade = 'f'; } }
there numerous problems code might not think are.
first off, public
wrong; c# requires public
.
second, use of local mgrade
strange , unnecessary, interestingly enough not wrong; legal assignment , return in 1 step that. in case not need to; return 'a';
without local assignment.
third, method misnamed because it not set grade
property. if intend set grade should void returning:
public void setgrade(float score) { if(score >= 90.0) { this.grade = 'a'; } this.grade = 'f'; }
if instead method intended conversion floats chars should static:
public static char scoretograde(float score) { if(score >= 90.0) { return 'a'; } return 'f'; }
frankly, i'd inclined both:
public void setgrade(float score) { this.grade = scoretograde(score); }
there, you've got best of both worlds.
fourth, stylistic point; might consider:
public char grade { get; private set; }
the compiler generate "invisible" backing field you, don't have manage yourself. syntax means grade
can read anywhere , written within class.
Comments
Post a Comment