Reputation: 6320
Why am I getting this error?
CS0029 Cannot implicitly convert type 'string' to 'UserQuery.Director'
I am getting this on:
m.DirectorName= "Someone";
Here is where it happens:
void Main()
{
Movie m = new Movie();
m.Name = "Matrix";
m.DirectorName = "Someone";
Console.WriteLine(m.Name);
}
public class Director
{
public string Name { get; set;}
}
public class Movie
{
public string Name { get; set;}
public Director DirectorName { get; set; }
}
Upvotes: 0
Views: 40
Reputation: 32693
DirectorName is not a string. So you can't assign a string to it. You can assign a Director to it. Since DirectorName property actually represents a Director, it's poorly named. Change your movie class to this:
public class Movie
{
public string Name { get; set; }
public Director MovieDirector { get; set; }
}
And your method code to this:
//Create a movie and set the name property
Movie m = new Movie();
m.Name = "Matrix";
//Create a director and set the name property
Director d = new Director();
d.Name = "Someone";
//Assign the director to the movie by setting the MovieDirector property
m.MovieDirector = d;
//Print out the movie's director's name.
Console.WriteLine(m.MovieDirector.Name);
There is also a shorthand syntax for this, using object initializers:
Movie m = new Movie
{
Name = "Matrix",
MovieDirector = new Director { Name = "Someone" }
};
Upvotes: 3
Reputation: 5862
DirectorName
is a type of Director
,you are trying to pass string value to it.
Upvotes: 0
Reputation: 1
In your class movie you have a reference to a class. If you want to change the string in the director class do m.DirectorName.Name
Upvotes: -1