Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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" });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading