Balagurunathan Marimuthu Balagurunathan Marimuthu - 2 months ago 8
C# Question

C#: Print POCO class's full qualified name without affect concatenation of any two string properties with the use of ToString() method

I have scenario to print the Student (First name and Last name) name of the

Student
class when I call the
ToString()
method of that class object like below.

Console.WriteLine(new Student() { FirstName = "Sachin", LastName = "Tendulkar" }.ToString());


So, I have
overrride
the
ToString()
method in
Student's POCO class
as below

namespace TestSOF_Console
{
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string StudentCode { get; set; }
public override string ToString()
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
}


Later, I have an additional query to get full qualified name of the
Student
class as
TestSOF_Console.Student
without affect Student full name with use of
ToString()
method.

Console.WriteLine(new Student() { FirstName = "Sachin", LastName = "Tendulkar" }.ToString());


The above code will allow me to choose what I need to print (whether class name or student name)...

Is there any possibility to achieve this both with
ToString()
method?

Answer

Add whatever literal string you want inside the quotes before the first brace, ("TestSOF_Console.Student - {0} {1}", FirstName, LastName)

If you need to make it optional simply overload the ToString() method:

public override string ToString()
{
    return string.Format("{0} {1}", FirstName, LastName);
}

public string ToString(string header)
{
    return string.Format(header + " - {0} {1}", FirstName, LastName);
}

To call the overload simply add a string as a parameter to the ToString() method-

new Student() { FirstName = "Sachin", LastName = "Tendulkar" }.ToString("TestSOF_Console.Student")

Comments