In the following code (edited for brevity), I want to override the behaviour of the .ToString() method. Using "override" only tells me that "no suitable method was found to override". If I use "new", it compiles and builds OK, but the code never uses the new ToString(). It just continues to use the native .NET .ToString() method.
Any idea what’s wrong?
public class Form_Processor {
public Form_Processor() {
SqlDataReader rs;
//SNIP database query
while (rs.Read()) {
result = rs["ReportDateTime"].ToString("dd");
}
rs.Close();
}
// **********************************************************
public new string ToString(string strFormat) {
if (strFormat != null) {
return "OK";
}
return null;
}
}
>Solution :
ToString() and ToString(string strFormat) are two different methods. ToString(string) is an overload and not an override of ToString().
The error message "no suitable method was found to override" is correct. Form_Processor is implicitly derived from Object and there is an Object.ToString() method but there is no ToString(string) overload on Object.
To override ToString() use public override string ToString() ....
…
Wow, this blog post is exactly what I was looking for! The clear explanations and sample code make it so easy to understand how to override the ToString() method. Thank you for sharing this helpful information!