eiu165 eiu165 - 2 months ago 10
C# Question

dynamic does not contain a definition for a property from a project reference

I am getting an error that says:


'object' does not contain a definition for 'Title'


all the code is also on github

I have a ConsoleApplication1 that looks like this

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Movie m = new Movie();
var o = new { Title = "Ghostbusters", Rating = "PG" };
Console.WriteLine(m.PrintMovie(o));
}
}
}


and Movie.cs

public class Movie : DynamicObject
{
public string PrintMovie(dynamic o)
{
return string.Format("Title={0} Rating={1}", o.Title, o.Rating);
}
}


it works fine from the SAME project, but if I add ConsoleApplication2 with a reference to ConsoleApplication1 and add the Exact same code

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Movie m = new Movie();
var o = new { Title = "Ghostbusters", Rating = "PG" };
Console.WriteLine(m.PrintMovie(o));
}
}
}


I get an error:


'object' does not contain a definition for 'Title'**


even though it is in the dynamic object.


  • o.Title 'o.Title' threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' dynamic {Microsoft.CSharp.RuntimeBinder.RuntimeBinderException}



Here is a screen shot: enter image description here

I am doing something like this and trying to call the movie function from a test project.

Answer

You need to use an ExpandoObject

 dynamic o = new ExpandoObject();
 o.Title = "Ghostbusters";
 o.Rating = "PG";

 Console.WriteLine(m.PrintMovie(o));