Guest User

Untitled

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