Reputation: 19
I have written a method in c# to get a count of a table, and saves the count in settings properties.
public static bool CompareCount(int? currentCount)
{
Properties.Settings.Default.Count = (int)currentCount;
Properties.Settings.Default.Save();
if (currentCount < Properties.Settings.Default.Count)
{
return false;
}
else
{
return true;
}
}
At first time if the count returned is 20. I will save it in the settings and I shud not compare that wiht the previous count. ON second time I want to compare the current count wiht the previoulsy saved count in settings. The above method should assign the current count for the first time . but on second time it shud compare.
thanks in advance.
Upvotes: 0
Views: 253
Reputation: 37576
Ask the current found Count to check if it is equal to the default value (zero, or not found or set your own once not found let say -1
), so once not found you do not compare otherwise compare the values.
For Example:
public static bool CompareCount(int? currentCount)
{
int foundCount = ReadFoundCountFromProperties;
if (foundCount != 0)
{
Properties.Settings.Default.Count = (int)currentCount;
Properties.Settings.Default.Save();
if (currentCount < foundCount)
return false;
return true;
}
Upvotes: 1
Reputation: 56727
First of all, think about what would happen when you cast the int?
that's coming in to int
if the parameter is null
. It doesn't make sense to use a nullable parameter if you don't do anything with it later on. You should either change the parameter type to int
or you could do this:
Properties.Settings.Default.Count = currentCount ?? 0;
Then, the method will always return true
, as the if
condition is always false
- remember you're setting Properties.Settings.Default.Count
to currentCount
just two lines above that? So how should it ever be larger than currentCount
?
You need to define for yourself how to determine "the first time" and "the second time". What's the condition to find out whether the method is run for the first time? For the code below I'll assume that there's some default value for Properties.Settings.Default.Count
that helps you determine whether the method runs for the first time.
Then, from what you say, your code should look like this:
public static bool CompareCount(int? currentCount)
{
int countValue = currentCount ?? 0;
if (Properties.Settings.Default.Count == <some default value>)
{
Properties.Settings.Default.Count = (int)currentCount;
Properties.Settings.Default.Save();
}
else
{
return currentCount >= Properties.Settings.Default.Count;
}
}
Upvotes: 2
Reputation: 33566
What is your problem in implementing it? You have all the blocks already here at hand. Just reorder them properly.
If the problem is that the "int Count" defined in settings is "0" by default, you can change it i.e. to default to -1 so it obviously will be NOT a Count written before. Or, you can change it to int?
to have default null..
Upvotes: 1