0

I want to add the value to null enum array. But I facing the null exception in run time. How can I fix this?

My Enum is

public enum Name
{
    Arun, Kumar, Mohan, Jerwin
}

Then I create the enum array.

private static Name[] names; //here I can`t set the size. Because user can pass the input as per their need. 

Now I get the value from user and add to enum array collecction. But I facing null exception in the code.

public static string GetName(Name input)
{
      names[0] = input;
      //My implementation            
}

I am getting the error in the line names[0] = input;.

My exception is

An unhandled exception of type 'System.NullReferenceException' occurred in my.dll

Additional information: Object reference not set to an instance of an object.

How can I add this user input to enum array?

Community
  • 1
  • 1
Arunkumar
  • 63
  • 10
  • Use a `List` or do you know beforehand how many entries `names` will have? I guess it's not only one, otherwise i don't understand why you need an array. – Tim Schmelter May 17 '18 at 09:21
  • 2
    `names` which is array is null, and you are trying to add things to it's 0th index – Amit May 17 '18 at 09:21
  • You should not use an enum for changing masterdata like names. If you want a new user you will have to change, recompile and deploy your code. – Tim Schmelter May 17 '18 at 09:23

1 Answers1

2

You don't need an array, because an array size should be fixed. You need a List<Name>. Lists have "dynamic" size and can have elements added.

private static List<Name> names = new List<Name>();

and then:

public static string GetName(Name input)
{
    names.Add(input)

(technically you could do this with an array, because arrays can be resized, but it is normally wrong to do it... There is the right tool for the right work)

Note that what you are doing is a little fishy... It smells bad. Using an enum (a construct that is decided at compile time and is normally used for small fixed sets) for something like a name is strange. There are normally uncountable number of names (with some small exceptions... there are only 50 names of USA states, and it is very rare that they change... There were only 7 kings of Rome, and this won't change and so on)

xanatos
  • 102,557
  • 10
  • 176
  • 249