I am currently converting from Vb6 to C# where the below Vb6 code is allowed :
Private Property Let gUnit(Optional bResolve As Boolean, aNoseHi)
gNoseLo(Optional parameter) = 0
End Property
Not Allowed:
void Test()
{
gNoseLo(false) = 0 //error occurs here
}
The gNoseLo
has been defined in VB6 as Private Property Get gNoseLo(Optional bResolve As Boolean)
. I cannot use a public property approach in C# since there are parameters so I used a method. What would be the correct way to recode the gNoseLo
to accept value assignment and prevent the error?
A "property with a parameter" in C# is an indexer. You can't give it a name like you can in VB though1. You declare it like this:
public int this[bool parameter]
{
get { ... }
set { ...}
}
Now that may or may not be appropriate for your use case. Alternatives are:
Have a regular property that returns something with an indexer:
public class IndexedByBoolean
{
public int this[bool parameter]
{
get { ... }
set { ...}
}
}
public class ContainsPropertyIndexedByBool
{
private readonly IndexedByBoolean index;
public IndexedByBoolean NoseLo { get { return index; } }
}
Then you could use foo.NoseLo[true] = 0
Use Get
and Set
methods:
SetNoseLo(true, 0);
1 Well, you specify a name, but not use it by that name.
See more on this question at Stackoverflow