This program is given in the following C# Corner website http://www.c-sharpcorner.com/Forums/Thread/153399/.
Problem with this code
string type = p.GetType().Name.ToLower();
In order to get the type p.GetType() is understood but to have it all lowercase letters it must be (p.GetType()).ToLower();
Please explain how did "Name" come in between? Problem is highlighted in the program.
using System;
interface person
{
String Name { get; set; }
}
class Poster : person
{
public String Name { get; set; }
}
class President : person
{
public String Name { get; set; }
public int Age { get; set; }
}
class Test
{
static void Main()
{
Poster po = new Poster();
po.Name = "Michell";
PrintDetails(po);
President pr = new President();
pr.Name = "Barack";
pr.Age = 50;
PrintDetails(pr);
Console.ReadKey();
}
static void PrintDetails(person p)
{
string type = p.GetType().Name.ToLower();
char initial = p.Name[0];
Console.WriteLine("{0} is a {1} and his initial is {2}", p.Name, type, initial);
}
}
/*
Michell is a poster and his initial is M
Barack is a president and his initial is B
*/
Loading
Posted Sep 4, 2012, 1:40 PM
RumaPosted Sep 4, 2012, 5:12 AM
class Test
{
static void Main()
{
int x = 10;
Type type = x.GetType();
/*Gets the fully qualified name of the System.Type, including the namespace of the System.Type but not the assembly.*/
string typeFullName_x = type.FullName.ToLower();
//Gets the name of the current member.
string typeName_x = type.Name.ToLower();
Console.WriteLine("Type of X:\nType =>{0}\nName => {1} \nFullName =>{2}",type.ToString(), typeName_x, typeFullName_x);
}
}
Output will be:
Type of X:
Type => System.Int32
Name => int32
FullName => system.int32
I think now it's easy to understand.
VulpesPosted Sep 4, 2012, 5:11 AM
Posted Sep 3, 2012, 7:06 PM
Let me modify the program so that code string type = p.GetType().Name.ToLower(); is replaced by p.GetType(); and in the Console.WriteLine() method "type" is replace by p.GetType(). The output is as follows:
//Michell is a Poster and his initial is M
//Barack is a President and his initial is B
The output is returns the Poster and President that means this is the type of the object "po" and "pr".
VulpesPosted Sep 3, 2012, 5:58 PM
This class has a property, Name, which returns the simple name of the type. The ToLower() method then converts it to all to lower case.
This Name property has nothing to do with the Name property of the person interface.
Notice also that p.GetType() returns the runtime type of 'p' (i.e. the type of object which 'p' actually refers to) rather than its compile time type.
So, while the compile type of 'p' is always person in the PrintDetails method, if you pass a Poster object then p.GetType().Name.ToLower() returns the string "poster".
Similarly, if you pass a President object, then it returns "president".
You can, of course, pass objects of these types to a person argument because Poster and President both implement the person interface.