Create Dictionary with custom class for value

I’m using a dictionary in C# and want to make the value a custom class. I have the following code.

public class myMovies
        {
           public string Name { get; set; }
           public string Year { get; set; }
        }
        Dictionary<string, myMovies> file_dict = new Dictionary<string, myMovies>();

        foreach (string file in Directory.GetFiles(path1, "*.mkv", SearchOption.AllDirectories))
        {
            file_dict.Add(file, new myMovies("x", "x");
        }

enter image description here

I’m doing something wrong, I just have no idea at this point. As a side note, this code does work when I just use a <string,string> dictionary and just store a text value in the value pair.

Edit
Required a constructor in my class definition. Thanks for help.

>Solution :

Either provide an appropriate constructor in the class definition:

public class myMovies
{
    public string Name { get; set; }
    public string Year { get; set; }

    public myMovies(string name, string year)
    {
        Name = name;
        Year = year;
    }
}

Or use object initializer syntax to assign the property values when instantiating the object:

        file_dict.Add(file, new myMovies { Name = "x", Year = "x" });

Leave a Reply