code_junkie

C#: Specifying behavior for the “default” keyword when using generics

Nov 13th, 2011
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.53 KB | None | 0 0
  1. public class GenericClass<T> where T : new() {
  2. //class definition
  3.  
  4. private void SomeMethod() {
  5. T myT = new T();
  6. //work with myT
  7. }
  8. }
  9.  
  10. public class foo
  11. {
  12. public string bar = "abc";
  13. }
  14.  
  15. public class Container<T>
  16. {
  17. T MaybeFoo = default;
  18. }
  19.  
  20. a = new Container<foo>();
  21.  
  22. // a.MaybeFoo is null;
  23.  
  24. public class foo
  25. {
  26. public string bar = "abc";
  27. }
  28.  
  29. public class Container<T> where T : new()
  30. {
  31. T MaybeFoo = new T();
  32. }
  33.  
  34. a = new Container<foo>();
  35.  
  36. Console.WriteLine( ((Foo)a.MaybeFoo).bar ) // prints "abc"
Add Comment
Please, Sign In to add comment