Abu Muhammad
Abu Muhammad

Reputation: 421

Using integer enum as a index for arrays in C# without converting?

I have a large collection of data, i need to store the same in string array.

this array then passed into another class as callback event.

so i need to use index as enum values so that outside person can read the string values easily.

for this i tried this,

public enum PublicData : int 
{
  CardNo = 0,
  CardName = 1,
  Address = 2,
   //etc....
}

then i have accessed this by,

string[] Publicdata = new string[iLength];
Publicdata[PublicData.CardNo] =  cardNovalue;

but here i am getting "invalid type for index - error"

How to resolve the same.

Upvotes: 3

Views: 2423

Answers (3)

MirrorBoy
MirrorBoy

Reputation: 869

Just cast your enum value

Publicdata[(int)PublicData.CardNo] =  cardNovalue;

Upvotes: 2

Mitulát báti
Mitulát báti

Reputation: 2166

Or you can go with an Extension method:

public static class MyEnumExtensions
{
    public static int Val(this PublicData en)
    {
        return (int)en;            
    }
}

Usage:

Publicdata[PublicData.Address.Val()];

Upvotes: 0

user1681317
user1681317

Reputation:

Create custom collection class and add indexer property with PublicData enum as indexer.

public enum PublicData : int
{
    CardNo = 0,
    CardName = 1,
    Address = 2,
}

public class PublicdataCollection
{
    private readonly string[] _inner;

    public string this[PublicData index]
    {
        get { return _inner[(int)index]; }
        set { _inner[(int) index] = value; }
    }

    public PublicdataCollection(int count)
    {
        _inner = new string[count];
    }
}

Upvotes: 3

Related Questions