I have an Grid UserControl. It used IFormatProvider to format Text in a Cell for display. Each Cell allows to set own IFormatProvider. On request of cell's DisplayText, program calls Cell's IFormatProvider, then Column's IFormatProvider in order. I make an array to save all non-identical IFormatProvider so that I just need to save ID to retrieve the format.
How to compare the IFormatProvider? If they are different, save into the array.
private IFormatProvider[] FormatProviders;
internal short CreateNewFormatProviders(IFormatProvider newFormatProvider)
{
if (newFormatProvider == null) // (IFormatProvider.Equals(newFormatProvider,null))
{
return -1;
}
int len = this.FormatProviders.Length;
for (int i = 0; i < len; i++)
{
if (IFormatProvider.Equals(this.FormatProviders[i],newFormatProvider))
{
return (short)i;
}
}
Array.Resize<IFormatProvider>(ref this.FormatProviders, len + 1);
this.FormatProviders[len] = newFormatProvider;
return (short)len;
}
In above code, I used IFormatProvider.Equals. Is it functioning or has better way?
Note: All types that I have for IFormatProvider
are custom and implement .ToString
that return unique values. If this is not the case for you this approach will not work.
After debug, I used .ToString() to check whether duplicated.
private IFormatProvider[] FormatProviders = new IFormatProvider[1];
internal short CreateNewFormatProviders(IFormatProvider newFormatProvider)
{
if (newFormatProvider == null) // (IFormatProvider.Equals(newFormatProvider,null))
{
return -1;
}
if (this.FormatProviders[0] == null)
{
this.FormatProviders[0] = newFormatProvider;
return 0;
}
int len = this.FormatProviders.Length;
for (int i = 0; i < len; i++)
{
//if (IFormatProvider.Equals(this.FormatProviders[i],newFormatProvider)) *always return False*
if (newFormatProvider.ToString() == this.FormatProviders[i].ToString())
{
return (short)i;
}
}
Array.Resize<IFormatProvider>(ref this.FormatProviders, len + 1);
this.FormatProviders[len] = newFormatProvider;
return (short)len;
}
testing code:
IFormatProvider newfmt1 = new CustomFormatProvider1();
IFormatProvider newfmt1_ = new CustomFormatProvider1();
IFormatProvider newfmt2 = new CustomFormatProvider2();
short index_newfmt1 = CreateNewFormatProviders(newfmt1);
short index_newfmt1_= CreateNewFormatProviders(newfmt1_);
short index_newfmt2= CreateNewFormatProviders(newfmt2);
Result is as I expect:
index_newfmt1 = 0
index_newfmt1_ = 0
index_newfmt2 = 1