Guest User

Untitled

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