Home > database >  Object behavior in C#
Object behavior in C#

Time:03-01

I have created two objects, str and prog. When I print both the objects

Output for Object 1: (The string is printed)

Web World!!

Output for Object 2: (The name of the Class is printed)

Program1

Can someone please explain why is this happening?

using System;
using System.Text;


public class Program1
{
    string str1;
    public Program1(string str2)
    {
        str1 = str2;
    }
}
public class Program
{
    public static void Main()
    {
        StringBuilder str = new StringBuilder("Web World!!", 30);
        Console.WriteLine(str);

        Program1 prog = new Program1("Hello");
        Console.WriteLine(prog);
    }
}

CodePudding user response:

This is because you the System does not know how it should print an object of type Program1, the way to tell the System how to print that type is to override the ToString method in the Program1 class. You can do this by simply adding:

public override string ToString() 
{
  return str1;
}

into the Program1 class. All C# objects naturally have this method but it will just return the class name (or some other value im not 100% sure) by default, we override this method to tell the System how to format an object of type Program1 as a string, allowing it to be printed correctly.

CodePudding user response:

Console.WriteLine(prog); prints Program1 because

Every class or struct in C# implicitly inherits the Object class. Therefore, every object in C# gets the ToString method, which returns a string representation of that object. (From How to override the ToString method (C# Programming Guide))

and

Default implementations of the Object.ToString method return the fully qualified name of the object's type. (From reference for Object.ToString Method)

Here's an example of a class overriding ToString (from the first article)

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override string ToString()
    {
        return "Person: "   Name   " "   Age;
    }
}

Record types

It may be worth to mention record types.

From Records (C# reference):

Record types have a compiler-generated ToString method that displays the names and values of public properties and fields. The ToString method returns a string of the following format:

 <record type name> { <property name> = <value>, <property name> = <value>, ...}

Example

If Program1 becomes a record, and str1 becomes a property rather than a field

public record Program1
{
    public string Str1 { get; set; }
    public Program1(string str1)
    {
        Str1 = str1;
    }
} 

then

Program1 prog = new Program1("Hello");
Console.WriteLine(prog);

prints

Program1 { Str1 = Hello }
  •  Tags:  
  • c#
  • Related