I have a class called Pin.
public class Pin { private string title; public Pin() { } public setTitle(string title) { this.title = title; } public String getTitle() { return title; } } From another class I add Pins objects in a List<Pin> pins and from another I want to iterate the List pins and get the elements. So I have this code.
foreach (Pin obj in ClassListPin.pins) { string t = obj.getTitle; } With this code I cannot retrieve the title. Why?
(Note: ClassListPin is just a static class which contains some elements and one of these, is the List<Pin> pins)
You need to add parentheses after a method call, else the compiler will think you're talking about the method itself (a delegate type), whereas you're actually talking about the return value of that method.
string t = obj.getTitle(); Extra Non-Essential Information
Also, have a look at properties. That way you could use title as if it were a variable, while, internally, it works like a function. That way you don't have to write the functions getTitle() and setTitle(string value), but you could do it like this:
public string Title // Note: public fields, methods and properties use PascalCasing { get // This replaces your getTitle method { return _title; // Where _title is a field somewhere } set // And this replaces your setTitle method { _title = value; // value behaves like a method parameter } } Or you could use auto-implemented properties, which would use this by default:
public string Title { get; set; } And you wouldn't have to create your own backing field (_title), the compiler would create it itself.
Also, you can change access levels for property accessors (getters and setters):
public string Title { get; private set; } You use properties as if they were fields, i.e.:
this.Title = "Example"; string local = this.Title;
getTitle is a function, so you need to put () after it.
string t = obj.getTitle();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With