Reputation: 5621
I have an abstract class used for caching that implements as follows (simplified)
public abstract class DataCacheMember<T> : List<T>
{
private List<T> _data;
public List<T> Data
{
get
{
if (_data == null || _data.Count() < 1)
_data = GetData();
return _data;
}
}
private string ApiEndPoint {get; set;}
private Timer timer;
private List<T> GetData()
{
//call api and get data
}
private void RefreshData()
{
_data = GetData();
}
protected DataCacheMember(string apiEndPoint)
{
ApiEndPoint = apiEndPoint;
timer = new System.Threading.Timer(
e => RefreshData(),
null,
TimeSpan.Zero,
TimeSpan.FromMinutes(10));
}
}
It allows for rapid creation of cached objects with a simple string for the api endpoint:
public class StateMap<Properties> : DataCacheMember<Properties>
{
public StateMap(string apiEndPoint = "Property/GetProperties")
: base(apiEndPoint)
{}
}
The whole reason for inheriting from List<T>
was to remove the need for the fields.
However, if I try to modify the constructor and refresh to:
private void RefreshData()
{
this = GetData() as DataCacheMember<T>;
}
protected DataCacheMember(string apiEndPoint)
{
this = GetData() as DataCacheMember<T>;
}
I get an error of Cannot assign to <this> because it is Read Only
.
What's the proper way to resolve this? Do I just need to use Clear()
and AddRange()
to manage the object?
If I do that, I see that the first call to the object will return empty, because the object can return before the constructor finishes it's call.
Upvotes: 0
Views: 64
Reputation: 9041
According to Using this() in C# Constructors
private void RefreshData()
{
this = GetData() as DataCacheMember<T>;
}
protected DataCacheMember(string apiEndPoint)
{
this = GetData() as DataCacheMember<T>;
}
These would only work in a struct and doesn't really do anything useful and is bad design.
Upvotes: 0
Reputation: 152511
To answer the question you cannot assign this
in a constructor or any other method. You could add the items returned from GetData()
:
private void RefreshData()
{
this.Clear();
this.AddRange(GetData());
}
protected DataCacheMember(string apiEndPoint)
{
this.Clear();
this.AddRange(GetData());
}
But inheriting form List<T>
probably isn't the right design here.
Upvotes: 3