How to?: If (textbox.name == null) without an NullReferenceException


  • I am writing some code, and I wanna "ask" if an object name is not null (aka, the object exist) then do some work, else, do other work...

    Of course, by doing "If (textbox.name == null)" I get the error NullReferenceException.

    Example of what I want to do in a function that have a public textbox object:
    private TextBox det;
    public TextBox Det
        get { return det; }
        set { det = value; }

    if (det.Name != "")
             Funciones.Detalle(det, CodBrowse, this.Text);
    Thursday, May 10, 2007 2:14 PM


All replies

  • Huumm...


    Code Snippet



      // work with the textbox...


       if(textbox.name !=null)


          // work with the textbox.name property...






    Is it?




    Thursday, May 10, 2007 2:20 PM
  • I am very new in C#, thank you alot for helping me.
    Aprovecho para preguntarte la dirección en español de MSDN, no se si la habrá.
    Thursday, May 10, 2007 2:34 PM
  • Thursday, May 10, 2007 2:39 PM
  • Hi, Gohalien

    When you create an object, like TextBox textBox1 = new TextBox(); there will be an instance of that object exists.

    When you just define an object (but not use new keywords) like TextBox textBox2; or TextBox textbox2 = null; there is no such an instance of TextBox created in memory.

    Since you looks as a very beginner with C#, here is a tutorial link for you:


    By the way, this forum is for English, so could you please input questions in english, so that other community members can read and help you with your questions.


    Monday, May 14, 2007 6:47 AM
  • You're most likely getting the NullReferenceException because you're attempting to access the Name property of det and det hasn't been initialised (i.e. it's set to null).


    Try stepping through your code with the VS.NET debugger and hover your mouse over the det variable when execution arrives at the line in question. If it's null, that's you're null object.


    Monday, May 14, 2007 8:33 AM