Object is a generic data type and every class you create in C# derives from a single class named System.Object.
When you have object data type instead of Employee data type program is not executing. Please explain the reason. Problem is highlighted.
using System;
public class CreateEmployee
{
public static void Main(string[] args)
{
Employee myAssistant = new Employee();
myAssistant.SetId(345);
Display(myAssistant);
Console.ReadKey();
}
static void Display(object num)
{
Console.WriteLine("ID # is {0}", num.GetId());
}
}
internal class Employee : Object
{
private int idNumber;
public int GetId()
{
return idNumber;
}
public void SetId(int id)
{
idNumber = id;
}
}
// ID # is 345
Loading
Posted Jul 13, 2013, 1:39 PM
VulpesPosted Jul 13, 2013, 11:59 AM
However, it doesn't follow that System.Object inherits all the members which are exclusive to the Employee class.
In fact, System.Object never inherits anything because it sits at the top of the inheritance tree.
Also, remember that when the compiler sees the type of the parameter defined as 'object' it has no idea what type of object will actually be passed to it.
All it can assume is that the object will certainly have System.Object's members and generate an error if anything else is used without a cast being applied first.
Posted Jul 13, 2013, 11:31 AM
VulpesPosted Jul 13, 2013, 11:23 AM
However, you can make it compile and run OK, by casting 'num' to its actual type:
static void Display(object num)
{
Console.WriteLine("ID # is {0}", ((Employee)num).GetId());
}