This is the problem:
object obj=new object();
obj=sender as Sender;
The second line doesn't change the compile-time type of obj
. It's still just object
. (And your first line that creates a new object
is completely pointless.) The compiler doesn't care what you've done with obj
when you try to use obj.name
- it cares about the compile-time type. You want:
Sender obj = (Sender) sender;
(See my recent blog post about why the cast is preferable over using as
here.)
You also want to use the public properties rather than the private fields:
Console.WriteLine("Sender is {0} and message is {1}", obj.Name, obj.Message);
Note that this casting is not unboxing, by the way - you have no value types involved (Sender
is a class) so there's no boxing or unboxing involved.