Reputation: 119
I am rather the Java-Guy, so handling getters/setters in C# is a little new to me. Why is this not working?
public String lastmodified {
get { return this.lastmodified; }
set
{
long ms = Int64.Parse(value);
var date = new DateTime(1970, 1, 1).AddSeconds(ms);
date.ToLocalTime();
this.lastmodified = date.ToString("HH_mm_yyyy");
}
}
value is in this cade a String which goes like 1987123019
Upvotes: 1
Views: 3486
Reputation: 164291
This will get you a StackOverflowException, since you are calling the property setter recursively in the last line of set
(and get
, for that matter). You need to assign the value to a field of a class, and read it from that field in the getter. Your current code simply calls into the same property accessor method infinitely, until you run out of stack space.
Common C# naming conventions suggests PascalCasing for property and method names, and camelCasing for instance variables, possibly prefixed with an underscore.
This code should work:
private string lastModified; // instance variable
public string LastModified
{
get { return this.lastModified; }
set
{
long ms = Int64.Parse(value);
var date = new DateTime(1970, 1, 1).AddSeconds(ms);
date = date.ToLocalTime();
this.lastModified = date.ToString("HH_mm_yyyy");
}
}
Also, "Not working" is kind of broad; but I am going to guess that you will see that the ToLocalTime
method does not get applied to the date. This is because DateTime
in C# is immutable, so it cannot be changed after construction. You will need to assign your date
variable to the result of ToLocalTime()
:
date = date.ToLocalTime();
Upvotes: 4
Reputation: 10184
For a property procedure, the getter should return the value of the class member variable holding the "wrapped" value. For a setter, the inbound value should be assigned to that class member variable. What you're doing makes the property self-referential.
Upvotes: 0
Reputation: 12849
Because you are assigning property itself on the last line. You should use either different casing or underscores to distinguish properties or fields.
I would recommend standard C# naming conventions. Also save the data in their native format. And also what driis said.
private DateTime lastModified;
public String LastModified {
get { return lastModified.ToString("HH_mm_yyyy"); }
set
{
long ms = Int64.Parse(value);
var date = new DateTime(1970, 1, 1).AddSeconds(ms);
date = date.ToLocalTime();
lastModified = date;
}
}
Upvotes: 8