0

I am trying to use something like string lists in C#.

Data format:

FamilyName: Trees

Values: [Banana, Neem, Pappaya, Coconut]

====

FamilyName: Animals

Values: [Cat, Dog, Pig, Tiger Lion]

Code I tried:

[DataContract(Name = "FamilyValuesMap", Namespace = "")]
    public class FamilyValuesMap
    {
        [DataMember(Name = "FamilyName", Order = 1)]
        public string FamilyName { get; set; }

        [DataMember(Name = "Values", Order = 2)]
        public List<string> Values { get; set; }
    }

    [CollectionDataContract(Name = "FamilyValuesMaps", ItemName = "FamilyValuesMap", Namespace = "")]
    public class FamilyValuesMaps : List<FamilyValuesMap>
    {
    }

In the following code I am trying to push the entries to the FamilyValuesMaps,

var FamilyValuesMaps = new FamilyValuesMaps();
FamilyValuesMaps.Add(new FamilyValuesMap { FamilyName = "Trees", Values = { "Banana", "Neem", "Pappaya", "Coconut" } });

I am not sure where the mess happening and the code not working it is returning the following error.

Data: {System.Collections.ListDictionaryInternal}
HResult: -2147467261
HelpLink: null
InnerException: null
Message: "Object reference not set to an instance of an object."
Source: null
StackTrace: null
TargetSite: null

Any suggestion or ideas would be helpful?

Community
  • 1
  • 1
Jeya Suriya Muthumari
  • 1,608
  • 2
  • 18
  • 39
  • 2
    Could it be that you need Add the values like: Values = new List() { "your","values","here" } – sander May 29 '18 at 10:33
  • 2
    How is this [Jagged Array](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/jagged-arrays) ? – Mike May 29 '18 at 10:34
  • This is just a list. The equivalent to a plain old string array. A jagged array is an array that contains *other* arrays. For example `string[][]` or `List>` – Panagiotis Kanavos May 29 '18 at 10:36
  • I could not answer because it was closed too soon. So this kind of collection initialization (`Values = { "Banana", "Neem", "Pappaya", "Coconut" }`) just calls the `Add` method so works only if the property is not null. Declare it as `public List Values { get; set; } = new List` and it will work. – György Kőszeg May 29 '18 at 10:44

1 Answers1

1

Your values List is not instantiated. See below.

var FamilyValuesMaps = new FamilyValuesMaps();
FamilyValuesMaps.Add(new FamilyValuesMap 
                            { 
                              FamilyName = "Trees", 
                              Values = new List<string>() 
                                  { 
                                      "Banana", 
                                      "Neem", 
                                      "Pappaya", 
                                      "Coconut" 
                                  } 
                             }
                     );
IronAces
  • 1,695
  • 1
  • 24
  • 31