I have an interface with a property, and a class that implements that interface. I cast an instance of the class to the interface, then attempt to read the property and it doesn't retrieve the value. Can anyone see why?
Interface:
public interface IFoo
{
int ObjectId { get; }
}
Class:
public class Bar : IFoo
{
public int ObjectId { get; set; }
}
Usage:
...
Bar myBar = new Bar() { ObjectId = 5 };
IFoo myFoo = myBar as IFoo;
int myId = myFoo.ObjectId; //Value of myFoo.ObjectId is 5 in Watch, but myId remains at 0 after statement
...
This is oversimplified, but essentially what I'm doing. Why can I see the value of myFoo.ObjectId in the watch window, but the assignment to myId fails (value is 0 before and after assignment)?
You might have manipulated the data on your watch through manual intervention or a statement that changed the value.
I did a quick test on your code in a Console Application and the value of myId is 5.
class Program
{
static void Main(string[] args)
{
Bar myBar = new Bar() { ObjectId = 5 };
IFoo myFoo = myBar as IFoo;
int myId = myFoo.ObjectId;
Console.WriteLine(myId); // 5
Console.ReadLine();
}
}
interface IFoo
{
int ObjectId { get; }
}
class Bar : IFoo
{
public int ObjectId { get; set; }
}