I have just started learning C#, and I am trying to a implement an interface with indexing properties that looks like this:
public interface ITest<T>
{
T this[int index] {get;}
int PropertyA {get;}
int PropertyB {get;}
}
public interface IProperties
{
float PropertyC {get;set;}
float PropertyD {get;set;}
}
public class Program : ITest<IProperties>
{
public int PropertyA => 3;
public int PropertyB => 1;
public float[] Temps = new float[10]
{
21, 22, 23, 24, 25, 26, 27, 28, 29, 30
};
private IProperties data;
public IProperties this[int index]
{
get
{
data.PropertyC = Temps[index];
data.PropertyD = Temps[index + 1];
return data[index];
}
set
{
data = value;
}
}
static void Main(string[] args)
{
Program program = new Program();
Console.WriteLine(program.PropertyA);
Console.WriteLine(program.PropertyB);
Console.WriteLine(program.Temps[0]);
Console.WriteLine(program[0].PropertyC); // expect 21
Console.WriteLine(program[0].PropertyD); // expect 22
}
}
At the end, I keep getting null exception in trying to get the value of program[0].PropertyC
. Where did it go wrong, and what shall I do to make it right?
**UPDATE: As much as I know that data
is a null and need to be instantiated, I need some ideas on how to instantiate data
as it is a interface type. Or is there any other way to get program[0].PropertyC
so data
wouldn't be used at the first place?