Guest User

Untitled

a guest
Sep 30th, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.68 KB | None | 0 0
  1. string foo = null;
  2. foo.ToUpper();
  3.  
  4. ref1.ref2.ref3.member
  5.  
  6. var r1 = ref1;
  7. var r2 = r1.ref2;
  8. var r3 = r2.ref3;
  9. r3.member
  10.  
  11. public class Person {
  12. public int Age { get; set; }
  13. }
  14. public class Book {
  15. public Person Author { get; set; }
  16. }
  17. public class Example {
  18. public void Foo() {
  19. Book b1 = new Book();
  20. int authorAge = b1.Author.Age; // You never initialized the Author property.
  21. // there is no Person to get an Age from.
  22. }
  23. }
  24.  
  25. Book b1 = new Book { Author = { Age = 45 } };
  26.  
  27. int[] numbers = null;
  28. int n = numbers[0]; // numbers is null. There is no array to index.
  29.  
  30. Person[] people = new Person[5];
  31. people[0].Age = 20 // people[0] is null. The array was allocated but not
  32. // initialized. There is no Person to set the Age for.
  33.  
  34. long[][] array = new long[1][];
  35. array[0][0] = 3; // is null because only the first dimension is yet initialized.
  36. // Use array[0] = new long[2]; first.
  37.  
  38. Dictionary<string, int> agesForNames = null;
  39. int age = agesForNames["Bob"]; // agesForNames is null.
  40. // There is no Dictionary to perform the lookup.
  41.  
  42. public class Person {
  43. public string Name { get; set; }
  44. }
  45. var people = new List<Person>();
  46. people.Add(null);
  47. var names = from p in people select p.Name;
  48. string firstName = names.First(); // Exception is thrown here, but actually occurs
  49. // on the line above. "p" is null because the
  50. // first element we added to the list is null.
  51.  
  52. public class Demo
  53. {
  54. public event EventHandler StateChanged;
  55.  
  56. protected virtual void OnStateChanged(EventArgs e)
  57. {
  58. StateChanged(this, e); // Exception is thrown here
  59. // if no event handlers have been attached
  60. // to StateChanged event
  61. }
  62. }
  63.  
  64. public class Form1 {
  65. private Customer customer;
  66.  
  67. private void Form1_Load(object sender, EventArgs e) {
  68. Customer customer = new Customer();
  69. customer.Name = "John";
  70. }
  71.  
  72. private void Button_Click(object sender, EventArgs e) {
  73. MessageBox.Show(customer.Name);
  74. }
  75. }
  76.  
  77. private Customer _customer;
  78.  
  79. public partial class Issues_Edit : System.Web.UI.Page
  80. {
  81. protected TestIssue myIssue;
  82.  
  83. protected void Page_Load(object sender, EventArgs e)
  84. {
  85. if (!IsPostBack)
  86. {
  87. // Only called on first load, not when button clicked
  88. myIssue = new TestIssue();
  89. }
  90. }
  91.  
  92. protected void SaveButton_Click(object sender, EventArgs e)
  93. {
  94. myIssue.Entry = "NullReferenceException here!";
  95. }
  96. }
  97.  
  98. // if the "FirstName" session value has not yet been set,
  99. // then this line will throw a NullReferenceException
  100. string firstName = Session["FirstName"].ToString();
  101.  
  102. // Controller
  103. public class Restaurant:Controller
  104. {
  105. public ActionResult Search()
  106. {
  107. return View(); // Forgot the provide a Model here.
  108. }
  109. }
  110.  
  111. // Razor view
  112. @foreach (var restaurantSearch in Model.RestaurantSearch) // Throws.
  113. {
  114. }
  115.  
  116. <p>@Model.somePropertyName</p> <!-- Also throws -->
  117.  
  118. <Grid>
  119. <!-- Combobox declared first -->
  120. <ComboBox Name="comboBox1"
  121. Margin="10"
  122. SelectedIndex="0"
  123. SelectionChanged="comboBox1_SelectionChanged">
  124. <ComboBoxItem Content="Item 1" />
  125. <ComboBoxItem Content="Item 2" />
  126. <ComboBoxItem Content="Item 3" />
  127. </ComboBox>
  128.  
  129. <!-- Label declared later -->
  130. <Label Name="label1"
  131. Content="Label"
  132. Margin="10" />
  133. </Grid>
  134.  
  135. private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
  136. {
  137. label1.Content = comboBox1.SelectedIndex.ToString(); // NullReference here!!
  138. }
  139.  
  140. var myThing = someObject as Thing;
  141.  
  142. void PrintName(Person p) {
  143. if (p != null) {
  144. Console.WriteLine(p.Name);
  145. }
  146. }
  147.  
  148. string GetCategory(Book b) {
  149. if (b == null)
  150. return "Unknown";
  151. return b.Category;
  152. }
  153.  
  154. string GetCategory(string bookTitle) {
  155. var book = library.FindBook(bookTitle); // This may return null
  156. if (book == null)
  157. throw new BookNotFoundException(bookTitle); // Your custom exception
  158. return book.Category;
  159. }
  160.  
  161. string GetTitle(int knownBookID) {
  162. // You know this should never return null.
  163. var book = library.GetBook(knownBookID);
  164.  
  165. // Exception will occur on the next line instead of at the end of this method.
  166. Debug.Assert(book != null, "Library didn't return a book for known book ID.");
  167.  
  168. // Some other code ...
  169.  
  170. return book.Title; // Will never throw NullReferenceException in Debug mode.
  171. }
  172.  
  173. DateTime? appointment = null;
  174. Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
  175. // Will display the default value provided (DateTime.Now), because appointment is null.
  176.  
  177. appointment = new DateTime(2022, 10, 20);
  178. Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
  179. // Will display the appointment date, not the default
  180.  
  181. IService CreateService(ILogger log, Int32? frobPowerLevel)
  182. {
  183. var serviceImpl = new MyService(log ?? NullLog.Instance);
  184.  
  185. // Note that the above "GetValueOrDefault()" can also be rewritten to use
  186. // the coalesce operator:
  187. serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5;
  188. }
  189.  
  190. var title = person.Title.ToUpper();
  191.  
  192. var title = person.Title == null ? null : person.Title.ToUpper();
  193.  
  194. var title = person.Title?.ToUpper();
  195.  
  196. // regular null check
  197. int titleLength = 0;
  198. if (title != null)
  199. titleLength = title.Length; // If title is null, this would throw NullReferenceException
  200.  
  201. // combining the `?` and the `??` operator
  202. int titleLength = title?.Length ?? 0;
  203.  
  204. object o = null;
  205. DateTime d = (DateTime)o;
  206.  
  207. <asp:Calendar runat="server" SelectedDate="<%#Bind("Something")%>" />
  208.  
  209. SqlConnection connection = null;
  210. connection.Open();
  211.  
  212. if (myvar != null)
  213. {
  214. // Go ahead and use myvar
  215. myvar.property = ...
  216. }
  217. else
  218. {
  219. // Whoops! myvar is null and cannot be used without first
  220. // assigning it to an instance reference
  221. // Attempting to use myvar here will result in NullReferenceException
  222. }
  223.  
  224. string testString = null; //Because it doesn't have a value (i.e. it's null; "Length" cannot do what it needs to do)
  225.  
  226. if (testString.Length == 0) // Throws a nullreferenceexception
  227. {
  228. //Do something
  229. }
  230.  
  231. Person p = null;
  232. p.Name = "Harry"; // NullReferenceException occurs here.
  233.  
  234. Person p = null;
  235. if (p!=null)
  236. {
  237. p.Name = "Harry"; // Not going to run to this point
  238. }
  239.  
  240. class Book {
  241. public string Name { get; set; }
  242. }
  243. class Car { }
  244.  
  245. Car mycar = new Car();
  246. Book mybook = mycar as Book; // Incompatible conversion --> mybook = null
  247.  
  248. Console.WriteLine(mybook.Name); // NullReferenceException
  249.  
  250. ComicBook cb = (ComicBook)specificBook;
  251.  
  252. ComicBook cb = specificBook as ComicBook;
  253. if (cb != null) {
  254. // ...
  255. }
  256.  
  257. string value = null;
  258. if (value.Length == 0) // <-- Causes exception
  259. {
  260. Console.WriteLine(value); // <-- Never reached
  261. }
  262.  
  263. object o = null;
  264. DateTime d = (DateTime)o; // NullReferenceException
  265.  
  266. DateTime? d = null;
  267. var s = d.ToString(); // OK, no exception (no boxing), returns ""
  268. var t = d.GetType(); // Bang! d is boxed, NullReferenceException
  269.  
  270. public static void MyExtension(this object x)
  271. {
  272. x.ToString();
  273. }
  274.  
  275. DateTime? d = null;
  276. d.MyExtension(); // Leads to boxing, NullReferenceException occurs inside the body of the called method, not here.
  277.  
  278. Contact contact = new Contact { Name = "Abhinav"};
  279. var context = new DataContext();
  280. context.Contacts.Add(contact);
  281. context.SaveChanges(); // NullReferenceException at this line
  282.  
  283. public class DataContext : DbContext
  284. {
  285. public DbSet<Contact> Contacts {get; set;}
  286. }
  287.  
  288. public partial class Contact
  289. {
  290. public string Name {get; set;}
  291. }
  292.  
  293. var x = myString.Trim();
  294.  
  295. var x = str1.Trim() + str2.Trim();
  296.  
  297. Public Class MyController
  298. {
  299. private ServiceA serviceA;
  300. private ServiceB serviceB;
  301.  
  302. public MyController(ServiceA serviceA, ServiceB serviceB)
  303. {
  304. this.serviceA = serviceA;
  305. this.serviceB = serviceB;
  306.  
  307. }
  308.  
  309. public void MyMethod()
  310. {
  311. //We don't need to check null because the dependency injection container injects it, provided you took care of bootstrapping it.
  312. var someObject = serviceA.DoThis();
  313. }
  314. }
  315.  
  316. string str = string.Empty;
  317. str.ToLower(); // throw null reference exception
  318.  
  319. Public Class Person {
  320. public string Name { get; set; }
  321. }
  322. Person objPerson;
  323. objPerson.Name /// throw Null refernce Exception
  324.  
  325. @{
  326. MyEntity M = new MyEntity();
  327. }
  328. @RenderPage("_MyOtherView.cshtml", M); // error in _MyOtherView, the Model was Null
  329.  
  330. @{
  331. MyEntity M = new MyEntity();
  332. }
  333. @Html.Partial("_MyOtherView.cshtml", M);
  334.  
  335. @inherits System.Web.Mvc.WebViewPage
  336. @{
  337. ViewBag.Title = "Entity Index";
  338. List<MyEntity> MyEntities = new List<MyEntity>();
  339. MyEntities.Add(new MyEntity());
  340. MyEntities.Add(new MyEntity());
  341. MyEntities.Add(new MyEntity());
  342. }
  343. <div>
  344. @{
  345. foreach(var M in MyEntities)
  346. {
  347. // Squiggly lines below. Hovering says: cannot convert method group 'partial' to non-delegate type Object, did you intend to envoke the Method?
  348. @Html.Partial("MyOtherView.cshtml");
  349. }
  350. }
  351. </div>
  352.  
  353. @foreach(var M in MyEntities){
  354. ...
  355. }
  356.  
  357. public X { get; set; }
  358.  
  359. public void InvokeX()
  360. {
  361. X.DoSomething(); // if X value is null, you will get a NullReferenceException
  362. }
  363.  
  364. //Using code contracts:
  365. [ContractInvariantMethod]
  366. protected void ObjectInvariant ()
  367. {
  368. Contract.Invariant ( X != null );
  369. //...
  370. }
  371.  
  372. public void DoSomething(MyObject obj) {
  373. if(obj == null)
  374. {
  375. throw new ArgumentNullException("obj", "Need a reference to obj.");
  376. }
  377. }
  378.  
  379. public void DoSometing([NotNull] obj)
  380.  
  381. [System.Diagnostics.DebuggerNonUserCode]
  382. public struct NotNull<T> where T : class
  383. {
  384. private T _value;
  385.  
  386. public T Value
  387. {
  388. get
  389. {
  390. if (_value == null)
  391. {
  392. throw new Exception("null value not allowed");
  393. }
  394.  
  395. return _value;
  396. }
  397. set
  398. {
  399. if (value == null)
  400. {
  401. throw new Exception("null value not allowed.");
  402. }
  403.  
  404. _value = value;
  405. }
  406. }
  407.  
  408. public static implicit operator T(NotNull<T> notNullValue)
  409. {
  410. return notNullValue.Value;
  411. }
  412.  
  413. public static implicit operator NotNull<T>(T value)
  414. {
  415. return new NotNull<T> { Value = value };
  416. }
  417. }
  418.  
  419. NotNull<Person> person = null; // throws exception
  420. NotNull<Person> person = new Person(); // OK
  421. NotNull<Person> person = GetPerson(); // throws exception if GetPerson() returns null
  422.  
  423. Person person = new Person { Name = "John" };
  424. WriteName(person);
  425.  
  426. public static void WriteName(NotNull<Person> person)
  427. {
  428. Console.WriteLine(person.Value.Name);
  429. }
  430.  
  431. Person person = GetPerson();
  432.  
  433. public static NotNull<Person> GetPerson()
  434. {
  435. return new Person { Name = "John" };
  436. }
  437.  
  438. Person person = (NotNull<Person>)GetPerson();
  439.  
  440. public static Person GetPerson()
  441. {
  442. return new Person { Name = "John" };
  443. }
  444.  
  445. [System.Diagnostics.DebuggerNonUserCode]
  446. public static class NotNullExtension
  447. {
  448. public static T NotNull<T>(this T @this) where T : class
  449. {
  450. if (@this == null)
  451. {
  452. throw new Exception("null value not allowed");
  453. }
  454.  
  455. return @this;
  456. }
  457. }
  458.  
  459. var person = GetPerson().NotNull();
  460.  
  461. var address = country?.State?.County?.City;
  462.  
  463. if (i == null) {
  464. // Handle this
  465. }
  466.  
  467. public class Student
  468. {
  469. private string FirstName;
  470. private string LastName;
  471. public string GetFullName()
  472. {
  473. return FirstName + LastName;
  474. }
  475. }
  476.  
  477. public class StudentInfo
  478. {
  479. public string GetStudentName()
  480. {
  481. Student s;
  482. string fullname = s.GetFullName();
  483. return fullname;
  484. }
  485. }
Add Comment
Please, Sign In to add comment