Search code examples
c#listgetter-setter

C#, getter/setter in List<cPoint> has error


I have the following code: below is the struct of the point

public struct cPoint
{
    public float x;
    public float y;
}

Below is the Datasource class (snipped)

    public class DataSource
    {
        private List<cPoint> samples;               // Data buffer goes here.
        //---------------------------------------------------------Getter/Setter
        .....
        public List<cPoint> Samples { get { return samples; } set { samples = value; }}

        // =====================================================constructor
        public DataSource(int ilength, string sName, Color cLine)
        {
            samples = CreateList<cPoint>(length);         
        }
}

and then

public void CalcSinusFunction_Riscy(DataSource src, double Freq, double ampFactor)
{
    int sampleRate = src.Length;
    double amplitude = ampFactor * UInt16.MaxValue;
    double frequency = Freq;
    for (int i = 0; i < src.Length; i++)
    {
        src.Samples[i].x = i;
        src.Samples[i].y = (float)(amplitude * Math.Sin((2 * Math.PI * (float)i * frequency) / sampleRate));
    }
}

It highlight an error, I not sure what I done wrong here, any solution?

Severity    Code    Description Project File    Line
Error   CS0029  Cannot implicitly convert type 'System.Collections.Generic.List<UDT_Term_FFT.cPoint>' to 'UDT_Term_FFT.cPoint[]'    UDT_Term_FFT    H:\007_ZMDI_Sync\007_ZMDI_zzDevelopment\002_Software\042_UDTermFFT-2C\UDTermFFT\ADT_Term_FFT\035_Scope\RiscyScope.cs    195
Error   CS1612  Cannot modify the return value of 'List<cPoint>.this[int]' because it is not a variable UDT_Term_FFT    H:\007_ZMDI_Sync\007_ZMDI_zzDevelopment\002_Software\042_UDTermFFT-2C\UDTermFFT\ADT_Term_FFT\035_Scope\RiscyScope.cs    143
Error   CS1612  Cannot modify the return value of 'List<cPoint>.this[int]' because it is not a variable UDT_Term_FFT    H:\007_ZMDI_Sync\007_ZMDI_zzDevelopment\002_Software\042_UDTermFFT-2C\UDTermFFT\ADT_Term_FFT\035_Scope\RiscyScope.cs    144

Solution

  • Regarding first error: we need to know there is line 195? It seems like it beyond your sample. Basically you can use "ToArray()" extension method.

    Second error occures because of cPoint is a structure. [] operator of List always returns the copy of that structure. So it is useless to modefy that copy and then immidiatly lose it (since it was not stored in any variable). You can change point by following code:

    src.Samples[i] = new cPoint()
    {
       x = i,
       y = (float)(amplitude * Math.Sin((2 * Math.PI * (float)i * frequency) / sampleRate))
    };