Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- string foo = null;
- foo.ToUpper();
- ref1.ref2.ref3.member
- var r1 = ref1;
- var r2 = r1.ref2;
- var r3 = r2.ref3;
- r3.member
- public class Book {
- public string Title { get; set; }
- }
- public class Example {
- public void Foo() {
- Book b1;
- string title = b1.Title; // You never initialized the b1 variable.
- // there is no book to get the title from.
- }
- }
- Book b1 = new Book();
- public class Person {
- public int Age { get; set; }
- }
- public class Book {
- public Person Author { get; set; }
- }
- public class Example {
- public void Foo() {
- Book b1 = new Book();
- int authorAge = b1.Author.Age; // You never initialized the Author property.
- // there is no Person to get an Age from.
- }
- }
- Book b1 = new Book { Author = { Age = 45 } };
- int[] numbers = null;
- int n = numbers[0]; // numbers is null. There is no array to index.
- Person[] people = new Person[5];
- people[0].Age = 20 // people[0] is null. The array was allocated but not
- // initialized. There is no Person to set the Age for.
- long[][] array = new long[1][];
- array[0][0] = 3; // is null because only the first dimension is yet initialized.
- // Use array[0] = new long[2]; first.
- Dictionary<string, int> agesForNames = null;
- int age = agesForNames["Bob"]; // agesForNames is null.
- // There is no Dictionary to perform the lookup.
- public class Person {
- public string Name { get; set; }
- }
- var people = new List<Person>();
- people.Add(null);
- var names = from p in people select p.Name;
- string firstName = names.First(); // Exception is thrown here, but actually occurs
- // on the line above. "p" is null because the
- // first element we added to the list is null.
- public class Demo
- {
- public event EventHandler StateChanged;
- protected virtual void OnStateChanged(EventArgs e)
- {
- StateChanged(this, e); // Exception is thrown here
- // if no event handlers have been attached
- // to StateChanged event
- }
- }
- public class Form1 {
- private Customer customer;
- private void Form1_Load(object sender, EventArgs e) {
- Customer customer = new Customer();
- customer.Name = "John";
- }
- private void Button_Click(object sender, EventArgs e) {
- MessageBox.Show(customer.Name);
- }
- }
- private Customer _customer;
- public partial class Issues_Edit : System.Web.UI.Page
- {
- protected TestIssue myIssue;
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- // Only called on first load, not when button clicked
- myIssue = new TestIssue();
- }
- }
- protected void SaveButton_Click(object sender, EventArgs e)
- {
- myIssue.Entry = "NullReferenceException here!";
- }
- }
- // if the "FirstName" session value has not yet been set,
- // then this line will throw a NullReferenceException
- string firstName = Session["FirstName"].ToString();
- // Controller
- public class Restaurant:Controller
- {
- public ActionResult Search()
- {
- return View(); // Forgot the provide a Model here.
- }
- }
- // Razor view
- @foreach (var restaurantSearch in Model.RestaurantSearch) // Throws.
- {
- }
- <p>@Model.somePropertyName</p> <!-- Also throws -->
- <Grid>
- <!-- Combobox declared first -->
- <ComboBox Name="comboBox1"
- Margin="10"
- SelectedIndex="0"
- SelectionChanged="comboBox1_SelectionChanged">
- <ComboBoxItem Content="Item 1" />
- <ComboBoxItem Content="Item 2" />
- <ComboBoxItem Content="Item 3" />
- </ComboBox>
- <!-- Label declared later -->
- <Label Name="label1"
- Content="Label"
- Margin="10" />
- </Grid>
- private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- label1.Content = comboBox1.SelectedIndex.ToString(); // NullReference here!!
- }
- var myThing = someObject as Thing;
- List<int> list = null;
- foreach(var v in list) { } // exception
- foreach (var node in myData.MyXml.DocumentNode.SelectNodes("//Data"))
- void PrintName(Person p) {
- if (p != null) {
- Console.WriteLine(p.Name);
- }
- }
- string GetCategory(Book b) {
- if (b == null)
- return "Unknown";
- return b.Category;
- }
- string GetCategory(string bookTitle) {
- var book = library.FindBook(bookTitle); // This may return null
- if (book == null)
- throw new BookNotFoundException(bookTitle); // Your custom exception
- return book.Category;
- }
- string GetTitle(int knownBookID) {
- // You know this should never return null.
- var book = library.GetBook(knownBookID);
- // Exception will occur on the next line instead of at the end of this method.
- Debug.Assert(book != null, "Library didn't return a book for known book ID.");
- // Some other code
- return book.Title; // Will never throw NullReferenceException in Debug mode.
- }
- DateTime? appointment = null;
- Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
- // Will display the default value provided (DateTime.Now), because appointment is null.
- appointment = new DateTime(2022, 10, 20);
- Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
- // Will display the appointment date, not the default
- IService CreateService(ILogger log, Int32? frobPowerLevel)
- {
- var serviceImpl = new MyService(log ?? NullLog.Instance);
- // Note that the above "GetValueOrDefault()" can also be rewritten to use
- // the coalesce operator:
- serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5;
- }
- var title = person.Title.ToUpper();
- var title = person.Title == null ? null : person.Title.ToUpper();
- var title = person.Title?.ToUpper();
- // regular null check
- int titleLength = 0;
- if (title != null)
- titleLength = title.Length; // If title is null, this would throw NullReferenceException
- // combining the `?` and the `??` operator
- int titleLength = title?.Length ?? 0;
- object o = null;
- DateTime d = (DateTime)o;
- <asp:Calendar runat="server" SelectedDate="<%#Bind("Something")%>" />
- SqlConnection connection = null;
- connection.Open();
- if (myvar != null)
- {
- // Go ahead and use myvar
- myvar.property = ...
- }
- else
- {
- // Whoops! myvar is null and cannot be used without first
- // assigning it to an instance reference
- // Attempting to use myvar here will result in NullReferenceException
- }
- string testString = null; //Because it doesn't have a value (i.e. it's null; "Length" cannot do what it needs to do)
- if (testString.Length == 0) // Throws a nullreferenceexception
- {
- //Do something
- }
- Person p = null;
- p.Name = "Harry"; // NullReferenceException occurs here.
- Person p = null;
- if (p!=null)
- {
- p.Name = "Harry"; // Not going to run to this point
- }
- class Book {
- public string Name { get; set; }
- }
- class Car { }
- Car mycar = new Car();
- Book mybook = mycar as Book; // Incompatible conversion --> mybook = null
- Console.WriteLine(mybook.Name); // NullReferenceException
- ComicBook cb = (ComicBook)specificBook;
- ComicBook cb = specificBook as ComicBook;
- if (cb != null) {
- // ...
- }
- string value = null;
- if (value.Length == 0) // <-- Causes exception
- {
- Console.WriteLine(value); // <-- Never reached
- }
- object o = null;
- DateTime d = (DateTime)o; // NullReferenceException
- DateTime? d = null;
- var s = d.ToString(); // OK, no exception (no boxing), returns ""
- var t = d.GetType(); // Bang! d is boxed, NullReferenceException
- public static void MyExtension(this object x)
- {
- x.ToString();
- }
- DateTime? d = null;
- d.MyExtension(); // Leads to boxing, NullReferenceException occurs inside the body of the called method, not here.
- var x = myString.Trim();
- var x = str1.Trim() + str2.Trim();
- Contact contact = new Contact { Name = "Abhinav"};
- var context = new DataContext();
- context.Contacts.Add(contact);
- context.SaveChanges(); // NullReferenceException at this line
- public class DataContext : DbContext
- {
- public DbSet<Contact> Contacts {get; set;}
- }
- public partial class Contact
- {
- public string Name {get; set;}
- }
- public class MyController
- {
- private ServiceA serviceA;
- private ServiceB serviceB;
- public MyController(ServiceA serviceA, ServiceB serviceB)
- {
- this.serviceA = serviceA;
- this.serviceB = serviceB;
- }
- public void MyMethod()
- {
- // We don't need to check null because the dependency injection container
- // injects it, provided you took care of bootstrapping it.
- var someObject = serviceA.DoThis();
- }
- }
- public X { get; set; }
- public void InvokeX()
- {
- X.DoSomething(); // if X value is null, you will get a NullReferenceException
- }
- //Using code contracts:
- [ContractInvariantMethod]
- protected void ObjectInvariant ()
- {
- Contract.Invariant ( X != null );
- //...
- }
- string str = string.Empty;
- str.ToLower(); // throw null reference exception
- Public Class Person {
- public string Name { get; set; }
- }
- Person objPerson;
- objPerson.Name /// throw Null refernce Exception
- @{
- MyEntity M = new MyEntity();
- }
- @RenderPage("_MyOtherView.cshtml", M); // error in _MyOtherView, the Model was Null
- @{
- MyEntity M = new MyEntity();
- }
- @Html.Partial("_MyOtherView.cshtml", M);
- @inherits System.Web.Mvc.WebViewPage
- @{
- ViewBag.Title = "Entity Index";
- List<MyEntity> MyEntities = new List<MyEntity>();
- MyEntities.Add(new MyEntity());
- MyEntities.Add(new MyEntity());
- MyEntities.Add(new MyEntity());
- }
- <div>
- @{
- foreach(var M in MyEntities)
- {
- // Squiggly lines below. Hovering says: cannot convert method group 'partial' to non-delegate type Object, did you intend to envoke the Method?
- @Html.Partial("MyOtherView.cshtml");
- }
- }
- </div>
- @foreach(var M in MyEntities){
- ...
- }
- public void DoSomething(MyObject obj) {
- if(obj == null)
- {
- throw new ArgumentNullException("obj", "Need a reference to obj.");
- }
- }
- public void DoSometing([NotNull] obj)
- [System.Diagnostics.DebuggerNonUserCode]
- public struct NotNull<T> where T: class
- {
- private T _value;
- public T Value
- {
- get
- {
- if (_value == null)
- {
- throw new Exception("null value not allowed");
- }
- return _value;
- }
- set
- {
- if (value == null)
- {
- throw new Exception("null value not allowed.");
- }
- _value = value;
- }
- }
- public static implicit operator T(NotNull<T> notNullValue)
- {
- return notNullValue.Value;
- }
- public static implicit operator NotNull<T>(T value)
- {
- return new NotNull<T> { Value = value };
- }
- }
- NotNull<Person> person = null; // throws exception
- NotNull<Person> person = new Person(); // OK
- NotNull<Person> person = GetPerson(); // throws exception if GetPerson() returns null
- Person person = new Person { Name = "John" };
- WriteName(person);
- public static void WriteName(NotNull<Person> person)
- {
- Console.WriteLine(person.Value.Name);
- }
- Person person = GetPerson();
- public static NotNull<Person> GetPerson()
- {
- return new Person { Name = "John" };
- }
- Person person = (NotNull<Person>)GetPerson();
- public static Person GetPerson()
- {
- return new Person { Name = "John" };
- }
- [System.Diagnostics.DebuggerNonUserCode]
- public static class NotNullExtension
- {
- public static T NotNull<T>(this T @this) where T: class
- {
- if (@this == null)
- {
- throw new Exception("null value not allowed");
- }
- return @this;
- }
- }
- var person = GetPerson().NotNull();
- var address = country?.State?.County?.City;
- public Class myClass
- {
- public int prop1 {get;set;}
- }
- public class Demo
- {
- public void testMethod()
- {
- myClass ref = null;
- ref.prop1 = 1; //This line throws error
- }
- }
- public class Demo
- {
- public void testMethod()
- {
- myClass ref = null;
- ref = new myClass();
- ref.prop1 = 1;
- }
- }
- public class Student
- {
- private string FirstName;
- private string LastName;
- public string GetFullName()
- {
- return FirstName + LastName;
- }
- }
- public class StudentInfo
- {
- public string GetStudentName()
- {
- Student s;
- string fullname = s.GetFullName();
- return fullname;
- }
- }
- if (i == null) {
- // Handle this
- }
- string postalcode=Customer.Address.PostalCode;
- //if customer or address is null , this will through exeption
- string postalcode=Customer?.Address?.PostalCode;
- //if customer or address is null , this will return null, without through a exception
- SqlConnection connection = null;
- connection.Open();
- System.NullReferenceException: Object reference not set to an instance of an object.
- if (connection != null){
- connection.Open();
- }
- class Program
- {
- static void Main(string[] args)
- {
- string str = null;
- Console.WriteLine(str.Length);
- Console.ReadLine();
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- MyClass1 obj;
- obj.foo(); //Use of unassigned local variable 'obj'
- }
- }
- public class MyClass1
- {
- internal void foo()
- {
- Console.WriteLine("hello from foo");
- }
- }
Add Comment
Please, Sign In to add comment