I've been tasked with converting some legacy code to a new system and we've got some VB6 structures that are here. Is there a way to convert them into a C# structure easily?
I could redefine the structure in C# but there's no fixed strings in C#. (Or maybe I misunderstand)
Any prods in the right direction?
Private Type MapRec
Name As String * NAME_LENGTH
Revision As Long
Moral As Byte
Up As Integer
Down As Integer
Left As Integer
Right As Integer
Music As String
BootMap As Integer
BootX As Byte
BootY As Byte
Tile() As TileRec
Npc(1 To MAX_MAP_NPCS) As Integer
NpcSpawn(1 To MAX_MAP_NPCS) As SpawnRec
TileSet As Integer
Region As Byte
End Type
With respect to fixed-length strings, yikes. It ain't gonna happen because there is no equivalent construct. Unless Jon Skeet or Anders Hejlsberg know differently and can be invoked to weigh in -- I don't think even they know a way, cuz there ain't one, I am pretty certain.
On the other hand, fixed-length strings are absolutely Satanic. Which is why they didn't include them in .NET. :-)
If you were to ask me how I would convert the above MapRec object to something usable in C#, well you kind of have your choice between a struct and a class. Personally, I dislike structs. If you used a class, then you could implement a kind of bastardized fixed-string by way of your setters and getters. As seen in this example, which is how I would implement your Type MapRec:
public class MapRec
{
private const int MAX_MAP_NPCS = 25;
private int fixedLength1 = 10;
private string _name;
public string Name
{
get
{
return _name;
}
set
{
if (value.Length != fixedLength1)
{
if (value.Length < fixedLength1)
{
_name = value.PadRight(fixedLength1);
}
else
{
_name = value.Substring(0,fixedLength1);
// or alternatively throw an exception if
// a 11+ length string comes in
}
}
else
{
_name = value;
}
}
}
// Constructor
public MapRec()
{
Npc = new int[MAX_MAP_NPCS];
NpcSpawn = new SpawnRec[MAX_MAP_NPCS];
}
public long Revision { get; set; }
public byte Moral { get; set; }
public int Up { get; set; }
public int Down { get; set; }
public int Left { get; set; }
public int Right { get; set; }
public string Music { get; set; }
public int BootMap { get; set; }
public byte BootX { get; set; }
public byte BootY { get; set; }
public TileRec[] Tile { get; set; }
public int[] Npc { get; set; }
public SpawnRec[] NpcSpawn { get; set; }
public int TileSet { get; set; }
public byte Region { get; set; }
}
In the end, unless one actually needs a fixed-length string (and perhaps Microsoft.VisualBasic.VBFixedStringAttribute could do the job), I would suggest staying the heck away from them.
You may be interested in the VBFixedStringAttribute, and the VBFixedArrayAttribute although they are only utilized in a few places.
See also this question and this question.