// A Class which doesn't override ToString
public Class Employee
{
}
// A Class which does override ToString
public Class Counter
{
private int theVal;
public Counter(int theVal)
{
this.theVal = theVal;
}
public override string ToString()
{
Console.WriteLine("Calling Counter.ToString()");
return theVal.ToString();
}
}
public Class Tester
{
// Note that Main has a capital M
// and is a static member of a Class
public static void Main()
{
// Create an instance of the Class
Tester t = new Tester();
// Call the non static member
t.Run();
}
// The non static Method which demonstrates
// calling ToString and boxing
public void Run()
{
Employee myEmploee = new Employee();
Counter myCounter = new Counter(12);
Console.WriteLine("The employee: {0}, the counter value: {1}",
myEmploee, myCounter);
// Note that integer literals and variables are boxed
int myInt = 5;
Console.WriteLine("Here are two integers: {0} and {1}", 17, myInt);
// Just to wair for an input
Console.ReadLine();
}
}
الخرج
Calling Counter.ToString()
The employee: Employee, the counter value: 12
Here are two integers: 17 and 5
public Class Employee
{
}
// A Class which does override ToString
public Class Counter
{
private int theVal;
public Counter(int theVal)
{
this.theVal = theVal;
}
public override string ToString()
{
Console.WriteLine("Calling Counter.ToString()");
return theVal.ToString();
}
}
public Class Tester
{
// Note that Main has a capital M
// and is a static member of a Class
public static void Main()
{
// Create an instance of the Class
Tester t = new Tester();
// Call the non static member
t.Run();
}
// The non static Method which demonstrates
// calling ToString and boxing
public void Run()
{
Employee myEmploee = new Employee();
Counter myCounter = new Counter(12);
Console.WriteLine("The employee: {0}, the counter value: {1}",
myEmploee, myCounter);
// Note that integer literals and variables are boxed
int myInt = 5;
Console.WriteLine("Here are two integers: {0} and {1}", 17, myInt);
// Just to wair for an input
Console.ReadLine();
}
}
الخرج
Calling Counter.ToString()
The employee: Employee, the counter value: 12
Here are two integers: 17 and 5