2
Answers

Get & Set Indexer

Photo of onez

onez

20y
2.1k
1
How can I both get and set a value in an object in my indexer? DataIdxer_Instance[3].Accum += 123000; Error - cannot modify the return value of ...DataIdxer.this[int] Because it is NOT a variable. public class DataIdxer { protected ArrayList Datas = new ArrayList(); public DataObj this[int idx] { get { if (idx > -1 && idx < Datas.Count) { return ((DataObj)Datas[idx]); } else { throw new InvalidOperationException("[Data indexer get item] index out of range"); } } set { if (idx > -1 && idx < Datas.Count) { Datas[idx] = value; } else if (idx == Datas.Count) { Datas.Add(value); } else { throw new InvalidOperationException("[Datas indexer set item outofrange]"); } } } } public struct DataObj { public Int64 Accum; public DataObj(int D) { Accum = D; } }

Answers (2)

0
Photo of bilnaad
NA 686 0 20y
I used your class and struct like below. And it worked fine. No errors at all. using System; using System.Collections; namespace csConsole { public class DataIdxer { protected ArrayList Datas = new ArrayList(); public DataObj this[int idx] { get { if (idx > -1 && idx < Datas.Count) { return ((DataObj)Datas[idx]); } else { throw new InvalidOperationException("[Data indexer get item] index out of range"); } } set { if (idx > -1 && idx < Datas.Count) { Datas[idx] = value; } else if (idx == Datas.Count) { Datas.Add(value); } else { throw new InvalidOperationException("[Datas indexer set item outofrange]"); } } } } public struct DataObj { public Int64 Accum; public DataObj(int D) { Accum = D; } public override string ToString() { return string.Format("{0}" ,Accum); } } class Test { public static void Main() { DataIdxer dix = new DataIdxer(); dix[0] = new DataObj(0); dix[1] = new DataObj(1); dix[2] = new DataObj(2); dix[3] = new DataObj(3); Console.WriteLine(((DataObj)dix[0])); Console.WriteLine(((DataObj)dix[1])); Console.WriteLine(((DataObj)dix[2])); Console.WriteLine(((DataObj)dix[3])); Console.Read(); } } }
0
Photo of eyes
NA 75 0 20y
Hi, If u change struct to class, hope it will work fine . . . ie., public struct DataObj to, public class DataObj Cheers, Kanna