How can I force a class to override the ToString() method?

  • Thread starter Thread starter AWHK
  • Start date Start date
Andreas,

You can do it like this:

public override string ToString()
{
// Do something.
return "This is a different string than what would be normally
returned";
}

Hope this helps.
 
AWHK said:
How can I force anyone who subclasses my class to override the ToString()
method?

Surprisingly enough, this is allowed:

abstract class Foo
{
public abstract override string ToString();
}
class Bar:Foo
{
public override string ToString()
{
return "Override";
}

}
 
Thanks Folks!

That worked well Steve.

Any idea how to force any subclasses to override operators?

like ie.
public static bool operator !=(MyType lhs, MyType rhs)

Guess i can throw a NotImplementedException, as recommended by Cody, in the
case of operators?

Andreas :-)
 
Yes, you can throw an exception in the base operator.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."
 
Surprisingly enough, this is allowed:
abstract class Foo
{
public abstract override string ToString();
}
class Bar:Foo
{
public override string ToString()
{
return "Override";
}

}

Very fascinating, I also didn't know that. But the principle is simple, it
simple sets the entry of the ToString() method in the vtable of the class
Foo to null.
 
AWHK said:
Any idea how to force any subclasses to override operators?

Again assuming the base class is abstract you could define the operators
in the base class and then delegate the calculation to abstract template
methods which the derived classes must define.

In the case of the equality operator you could define the == and !=
operators in the base class and force Equals() and GetHashCode() to be
overridden using an abstract override in the same way as ToString().
 
throw a NotImplementedException in your ToString() method to indicate that
ToString() should be overridden.
 
Back
Top