-2

I am not sure if this has already been asked since I am not sure how to phrase this properly.

class Program {
  public static void Main (string[] args) 
  {
    Console.WriteLine ("Start:");
    Example thing = new Example();
    Console.WriteLine(thing);
  }
}

This would write the type of object:

>> Example

Whereas I would like it to print a value that the Example object would have.

Is this possible and, if so, how would I do this?

EDIT: I would like it to output like this (if "hello" was the contents of the variable I want to output):

Console.WriteLine(thing);

Output:

>> hello
Ciaran
  • 7
  • 2
  • 3
    See https://learn.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method. Did you even searched a bit? This question was asked so many times before. – MakePeaceGreatAgain Jan 10 '18 at 11:53
  • Create a override method ToString() in Example class. Return rewuired data from the method then you can call that statement to print. – Subash Kharel Jan 10 '18 at 11:54
  • 2
    For me, the answer is in the 3rd Google result: [MSDN](https://msdn.microsoft.com/en-us/library/system.object.tostring(v=vs.110).aspx) – Thomas Weller Jan 10 '18 at 11:56
  • @ThomasWeller That duplicate is quite poor, as serializing to JSON is quite overkill here. – MakePeaceGreatAgain Jan 10 '18 at 11:58
  • Google for: "write object to console c#" immediately yields many examples on how to do this. – MakePeaceGreatAgain Jan 10 '18 at 12:00
  • it seems you are not clear about what value an `object` has. `thing` is of type `Example` and what you want to print out is a `string`. So these two are different types! `thing` cannot (by definition) have the value of `"hello"`! either a property in the class `Example` can be of type `string` and have the value `"hello"` or `thing` needs to be of type `string`. A third possibility is that you override the `ToString` method and simply return `return "hello";` from the method. – Mong Zhu Jan 10 '18 at 12:00
  • @HimBromBeere: do not only look at the accepted answer. 3+ other answers tell to override the ToString() method. – Thomas Weller Jan 10 '18 at 12:08

1 Answers1

4

You'll need to override and implement the object.ToString() method, e.g.

public class Example {
    ...
    public override string ToString()
    {
        return this.SomeProperty;
    }
}
Chris Pickford
  • 8,642
  • 5
  • 42
  • 73
  • Thanks so much! Also, is it possible to do this with integers and other variable types? – Ciaran Jan 10 '18 at 11:57
  • Most native types will already have a `.ToString()` implementation, so yes you could use `return this.IntProperty.ToString();` or even use string interpolation `return $"The value is: {this.IntProperty}";`. – Chris Pickford Jan 10 '18 at 12:00