In VB.NET you can use an object initializer and reference the same members on the right hand side, like this:
GetValue.Add(New ArrayIndexInfo() With {
.Type = CType(NvpInfo(Index), Type),
.Name = NvpInfo(Index + 2).ToString,
.NvpValues = CType(.Type.GetField(NvpInfo(Index + 1).ToString).GetValue(Instances.First(Function(o) o IsNot Nothing AndAlso o.GetType = CType(NvpInfo(Index), Type))), NameValuePair())
})
Notice how in the line that sets .NvpValues
you can reference .Type
and that it's no problem.
But if you try to do that in c# (or like I did, try to convert a project from vb.net to c#), you get an error.
<variable> is not declared
I worked around it like this, which is not DRY because ((Type)NvpInfo[Index])
is repeated:
functionReturnValue.Add(new ArrayIndexInfo {
Type = (Type)NvpInfo[Index],
Name = NvpInfo[Index + 2].ToString(),
NvpValues = (NameValuePair[])((Type)NvpInfo[Index]).GetField(NvpInfo[Index + 1].ToString()).GetValue(Instances.First(o => o != null && o.GetType() == (Type)NvpInfo[Index]))
});
- Why doesn't c# allow this? I think it should. I think converting legacy code to c# should be as painless as possible.
- Is there a better way that I get around this and still use the object initializer?