c# - Why writing items to console writes only namespace and class name instead of data? -
this question has answer here:
- writeline class 9 answers
probably title doesn't sound of guys (skilled programmers), i'm on 3rd week of learning c# fundamentals , cant figure out how solve next task. shall store temperatures bunch of cities, asking user cityname first , actual temp in city. stuff should saved in list<> , shall use class , constructor. when try print out result (using foreach) prints out name of namespace , name of class "task_5.city" whats wrong code:
public class city //class { public string cityname { get; set; } public int temperature { get; set; } public city(string name, int temp)//konstruktor { this.cityname = name; this.temperature = temp; } } class program { static void main(string[] args) { var citylist = new list<city>(); console.writeline("what city?"); string cityname = console.readline(); console.writeline("what temperature city?"); int temp = convert.toint32(console.readline()); city mycity = new city(cityname, temp); citylist.add(mycity); foreach (var item in citylist) { console.writeline(item); } console.readline(); } }
you passing object console.writeline(item) instead of passing string. console.writeline invokes tostring() method of object default returns namespace+class name. can override behavior next:
public class city //class { public string cityname { get; set; } public int temperature { get; set; } public city(string name, int temp)//konstruktor { this.cityname = name; this.temperature = temp; } public override string tostring() { return string.format("{0} {1}", cityname, temperature); } } or can use overload of writeline method:
console.writeline("{0} {1}", item.cityname, item.temperature);
Comments
Post a Comment