-2

Using this example code:

public class Product
{
    private Boolean _active;

    public Boolean active
    {
        get
        {
            return _active;
        }
        set
        {
            _active = value;
        }
    }
}

Product p = new Product();
p.active = true;

How can I override the ToString() method so I can use this:

MessageBox.Show(p.active.ToString());
hardkoded
  • 18,915
  • 3
  • 52
  • 64
  • 2
    Why do you want to do that? To display Yes/No instead of True/False? – Julien Jun 08 '17 at 12:19
  • Are you maybe getting a compile error because you are trying to use `ToString()` method and have incorrect capitalization? Can you be more clear about the problem? – user700390 Jun 08 '17 at 12:22

3 Answers3

4

For what it's worth, you could use an extension method:

public static string toString(this bool b)
{
    return b ? "Si" : "No";
}

MessageBox.Show(p.active.toString());

That works because of your typo, toString instead of ToString.

You can't change the return value of a method without changing it. Boolean.ToString returns either "True" or "False" and nothing can change that (apart from Microsoft).

But of course you could also write:

MessageBox.Show(p.active ? "Si" : "No");
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    I think that is open to confusion since the name is so similar to the existing method. But the concept is great - AsYesNo (AsSiNo perhaps?) or something like that would be a great solution! – mjwills Jun 08 '17 at 12:24
  • Hi. Thanks for you answer but i would like to access "p.active.ToString()" and not "p.ToString()". – user2845025 Jun 08 '17 at 13:29
  • 1
    @user2845025: my code works with `MessageBox.Show(p.active.toString());`. You can't change the actual implementation of a method without changing it. [`Boolean.ToString`](https://msdn.microsoft.com/en-us/library/atahsch6(v=vs.110).aspx) returns either `"True"` or `"False"`. – Tim Schmelter Jun 08 '17 at 13:35
1

I`m not sure you can override it like you want. Maybe you could just use ternary operator in order to have a small evaluation, like

MessageBox.Show(p.active ? 'Yes' : 'No');
Tutch
  • 281
  • 1
  • 4
  • 12
  • Hi. Thanks for you reply. I am already using it like you said but I wounder if there is a better way. If I have to use this one hundred times, I'll prefer to use `MessageBox.Show(p.active.toString());` instead of `MessageBox.Show(p.active ? 'Yes' : 'No');` – user2845025 Jun 08 '17 at 13:37
  • @user2845025: If this was possible you would change the behaviour of a method as side-effect for every other using it. That would be evil – Tim Schmelter Jun 08 '17 at 14:11
-1

Why overriding the ToString of a variable instead of the ToString of the object? Can you explain more your scenario? Rather than create an extension method that will treat all the "bool" as "Yes" or "No" when you invoke the ToString on the variable, I suggest you to use the ToString of the object or use attributes to display your information

class Program
{
    static void Main(string[] args)
    {
        Product p = new Product();
        Console.WriteLine(p);
        Console.ReadLine();
    }
}

public class Product
{
    private Boolean _active;

    public Boolean active
    {
        get
        {
            return _active;
        }
        set
        {
            _active = value;
        }
    }

    public override string ToString()
    {
        return active ? "Yes" : "No";
    }
}

If you want to use attributes, you can create an extension method with the approach described here https://stackoverflow.com/a/672212/819153

class Program
{
    static void Main(string[] args)
    {
        Product p = new Product();
        var attValue = Helper.ToStringProperty(p, prod => prod.active);
        Console.WriteLine(attValue);
        Console.ReadLine();
    }
}

public class Product
{
    private Boolean _active;

    [Display(Name = "Super Active")]
    public Boolean active
    {
        get
        {
            return _active;
        }
        set
        {
            _active = value;
        }
    }
}

public class Helper
{
    public static string ToStringProperty<TSource, TProperty>(TSource source,
        Expression<Func<TSource, TProperty>> propertyLambda)
    {
        Type type = typeof(TSource);

        MemberExpression member = propertyLambda.Body as MemberExpression;
        if (member == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a method, not a property.",
                propertyLambda.ToString()));

        PropertyInfo propInfo = member.Member as PropertyInfo;
        if (propInfo == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a field, not a property.",
                propertyLambda.ToString()));

        if (type != propInfo.ReflectedType &&
            !type.IsSubclassOf(propInfo.ReflectedType))
            throw new ArgumentException(string.Format(
                "Expresion '{0}' refers to a property that is not from type {1}.",
                propertyLambda.ToString(),
                type));

        var output = source.ToString();
        var attribute = propInfo.GetCustomAttributes(typeof(DisplayAttribute), false).Cast<DisplayAttribute>().FirstOrDefault();

        return attribute != null ? attribute.Name : output;
    }
}
Zinov
  • 3,817
  • 5
  • 36
  • 70