Override .ToString method c# -
okay, wrote program out of exercise of c# programming book (i'm trying learn here) , asks "override tostring() method return data members".
have done correctly? or have wrote code compiles nothing. purpose of tostring?
i have spent 30 minutes looking @ other posts on , havn't figured out, decided make this.
using system; using system.collections.generic; using system.linq; using system.text; namespace consoleapplication297 { class program { static void main(string[] args) { string name = "stormtrooper"; employee s = new employee(name); console.writeline("the type of hire {0}", s.name); console.writeline("the identification number {0}", s.number); console.writeline("the date of hire {0} aby", s.date); console.writeline("the standard galactic salary is...{0:c}", s.salary); } class employee { private string _name; private string _number; private int _date; private int _salary; public string name { { return _name; } } public string number { { return _number; } } public int date { { return _date; } } public int salary { { return _salary; } } public employee(string n) { _name = n; _number = "aa23tk421"; _date = 4; _salary = 800; } } public override string tostring() { return "_name + _number + _date + _salary".tostring(); } } }
you returning string says phrase _name + _number + _date + _salary
.
what wanted build string using fields. if wanted them mushed concat work, highly un-readable
public override string tostring() { return string.concat(_name, _number, _date, _salary); }
however better use format , include labels values
public override string tostring() { return string.format("name: {0}, number:{1}, date:{2}, salary:{3}",_name, _number, _date, _salary); }
Comments
Post a Comment