2

I am trying to initialize a list of type Movie in class other than Movie while both the classes are in the same namespace. Code is mentioned underneath:

namespace MovieListCaseStudy
{
    class Movie
    {
        private int id;

        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private float duration;

        public float Duration
        {
            get { return duration; }
            set { duration = value; }
        }
        private float price;

        public float Price
        {
            get { return price; }
            set { price = value; }
        }
    }
}

******

namespace MovieListCaseStudy
{
    class BusinessLogic
    {
        List<Movie> movielist = new List<Movie>();
        {
            {Id=1, Name="pk", Duration=2, Price=200}

        };
    }
}

the problem is that Id, Name etc. attributes are not being identified in the BusinessLogic class. Kindly help.

1
  • 1
    Side note: durations should by public TimeSpan Duration {get;set;} and price (as all money related values) should be public decimal Price {get;set;}. Commented Jan 3, 2015 at 7:46

2 Answers 2

4

You're missing new Movie():

List<Movie> movielist = new List<Movie>()
{
    new Movie() { Id=1, Name="pk", Duration=2, Price=200 }
};
Sign up to request clarification or add additional context in comments.

Comments

2

Remove the trailing semi colon, and as per @Marcin, construct with new Movie(). Also note that default constructor parenths () are optional with initializers:

class BusinessLogic
{
    List<Movie> movielist = new List<Movie>
    {
        new Movie {Id=1, Name="pk", Duration=2, Price=200}
    };
}

As an aside, another shorthand is possible with Array initialization, although in this case it would require an additional .ToList() conversion which would be less efficient in this case:

class BusinessLogic
{
    List<Movie> movielist = new [] // No type needed, will be inferred
    {
        new Movie {Id=1, Name="pk", Duration=2, Price=200}
    }
    .ToList();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.