code_junkie

C#: Force Compiler error on use of myObj.ToString()

Nov 11th, 2011
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. using System;
  2.  
  3. public class Foo
  4. {
  5. public int ID = 123;
  6. public string Name = "SomeName";
  7.  
  8. private string ToString() { return null; }
  9. }
  10.  
  11. public class MyClass
  12. {
  13. public static void Main()
  14. {
  15. Foo myObj = new Foo();
  16. WL("I want this to be a compiler error: {0}", myObj.ToString());
  17. RL();
  18. }
  19.  
  20. #region Helper methods
  21.  
  22. private static void WL(object text, params object[] args)
  23. {
  24. Console.WriteLine(text.ToString(), args);
  25. }
  26.  
  27. private static void RL()
  28. {
  29. Console.ReadLine();
  30. }
  31.  
  32. #endregion
  33. }
  34.  
  35. [Obsolete("Use the XYZ properties instead of .ToString() on Foobar", true)]
  36.  
  37. [Obsolete("dont' use", true)]
  38. public override string ToString()
  39. {
  40. throw new Exception("don't use");
  41. }
  42.  
  43. Foo myObj = new Foo();
  44.  
  45. Console.WriteLine(myObj);
  46.  
  47. public string CreateItemUrl(int itemId)
  48. {
  49. return string.Format("someurl.aspx?id={0}", itemId);
  50. }
  51.  
  52. CreateItemUrl(myObj.Id);
  53.  
  54. string theUrl = string.Format("someurl.aspx?id={0}", myObj);
  55.  
  56. public new void ToString() { }
Add Comment
Please, Sign In to add comment