-3

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.

Dayton Brown
  • 1,228
  • 3
  • 16
  • 31
  • 1
    you can reduce the question to: how create a new instance of myMovies class. – Sir Rufo Feb 14 '23 at 23:31
  • @SirRufo, add that as an answer and I'll mark it. I just needed the correct search. https://stackoverflow.com/questions/34719077/declaring-a-new-instance-of-class-with-or-without-parentheses – Dayton Brown Feb 14 '23 at 23:34
  • The my Movies class doesn't have a constructor with two string arguments. Your IDE should tell you that, this code doesn't build and I don't believe there's no error reported somewhere (unless you're using notepad) – David Libido Feb 14 '23 at 23:36

2 Answers2

1

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" });
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
0

It's telling you it expects a Constructor, so give it what it expects:

public class myMovies
{
    public myMovies(string name, string year)
    {
         Name = name;
         Year = year;
    }
    public string Name { get; set; }
    public string Year { get; set; }
}
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321