Hola!
I tried the following public implementation of interface indexer by struct (Code Snippet 1) in private and explicit implementation by struct (Code Snippet 2) but in vain.
Please help!
Code Snippet 1:
// indexers in interface, public implementation by struct
using System;
interface MyInterface
{
int this[int index]
{
get;
set;
}
}
struct MyStruct : MyInterface
{
int[] array;
public int l;
public bool error;
public MyStruct(int size) : this()
{
array = new int[size];
l = size;
}
public int this[int index]
{
get
{
if(ok(index))
{
error = false;
return array[index];
}
else
{
error = true;
return 0;
}
}
set
{
if(ok(index))
{
array[index] = value;
error = false;
}
else
error = true;
}
}
bool ok(int index)
{
if((index>=0) && (index<l))
return true;
else
return false;
}
}
struct MainStruct
{
static void Main()
{
MyStruct ms = new MyStruct(5);
int x;
Console.WriteLi ne("Fail quietly: ");
for(int i=0; i<(ms.l*2); i++)
ms = i;
for(int i=0; i<(ms.l*2); i++)
{
x = ms;
if(x!=-1)
Console.Write(x + " ");
}
Console.WriteLi ne("\nFail with error reports: ");
for(int i=0; i<(ms.l*2); i++)
{
ms = i;
if(ms.error) // *Note: Works well
Console.WriteLi ne("ms[ " + i + " ] out-of-bounds");
}
for(int i=0; i<(ms.l*2); i++)
{
x = ms;
if(!ms.error) // *Note: Works well
Console.Write(x + " ");
else
Console.WriteLi ne("ms[ " + i + " ] out-of-bounds");
}
}
}
Code Snippet 2:
// indexers in interface, private and explicit implementation by struct
using System;
interface MyInterface
{
int this[int index]
{
get;
set;
}
}
struct MyStruct : MyInterface
{
int[] array;
public int l;
public bool error;
public MyStruct(int size) : this()
{
array = new int[size];
l = size;
}
int MyInterface.thi s[int index]
{
get
{
if(ok(index))
{
error = false;
return array[index];
}
else
{
error = true;
return 0;
}
}
set
{
if(ok(index))
{
array[index] = value;
error = false;
}
else
error = true;
}
}
bool ok(int index)
{
if((index>=0) && (index<l))
return true;
else
return false;
}
}
struct MainStruct
{
static void Main()
{
MyStruct ms = new MyStruct(5);
int x;
MyInterface mi = (MyInterface)ms ;
Console.WriteLi ne("Fail quietly: ");
for(int i=0; i<(ms.l*2); i++)
mi = i;
for(int i=0; i<(ms.l*2); i++)
{
x = mi;
if(x!=-1)
Console.Write(x + " ");
}
Console.WriteLi ne("\nFail with error reports: ");
for(int i=0; i<(ms.l*2); i++)
{
mi = i;
if(ms.error) // *Note: Doesn't work
Console.WriteLi ne("mi[ " + i + " ] out-of-bounds");
}
for(int i=0; i<(ms.l*2); i++)
{
x = mi;
if(!ms.error) // *Note: Doesn't work
Console.Write(x + " ");
else
Console.WriteLi ne("mi[ " + i + " ] out-of-bounds");
}
}
}
Thanks