3

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.

2
  • 1
    There's a discussion about this here : stackoverflow.com/questions/443935/… Commented Nov 17, 2016 at 9:21
  • Sounds to me like those should not be enum members at all, but properties of a data class. Commented Nov 17, 2016 at 9:23

3 Answers 3

3

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];
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Looked for an easy or inbuilt c# answer for this. but this seems to converting to int inside the class, and i don't know about the performance if i called this inside the thread routine. finally just converting to int better than this since i need code performance. thanks for pinging.
2

Just cast your enum value

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

Comments

0

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()];

2 Comments

@ bati, Dear , i know this, but As i mentioned in my question title i need answer without converting to int.
Why not just return (int)en;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.