Results 1 to 4 of 4

Thread: How to check if variable exists in C#

  1. #1
    Join Date
    Jun 2009
    Posts
    92

    How to check if variable exists in C#

    I am creating a program in C#. My problem is that I am unable to find a proper method to check if a variable defined in my program exists or not. For example, if I have created a global variable say "x" and I am calling this variable in some block. According to my code, it should first check it just to make sure if it has been created and if it is created then perform the operations but if it is not then display the message that it is not declared. Logic is proper but the problem is that how can I check if that variable exists in C#? What method should I use for this?

  2. #2
    Join Date
    May 2008
    Posts
    2,012

    Re: How to check if variable exists in C#

    But why you want to use method. You can use a Try Catch block to handle your exception. Because since you are declaring a global variable there is less possibility of variable not existing. So try catch block should do your work.

    If you don't know than here is how you use try catch:

    Code:
    try
    {
    //YOUR STATEMENT
    }
    catch
    {
    //YOUR STATEMENT
    }

  3. #3
    Join Date
    May 2008
    Posts
    685

    Re: How to check if variable exists in C#

    "If Else" block should also solve your problem. You can use code like below:

    Code:
    if(Exists(VARIABLE))
    {
      //perform the operation
    }
    else
    {
      // display your message
    }

  4. #4
    Join Date
    Nov 2008
    Posts
    996

    Re: How to check if variable exists in C#

    I think what I have understand about your problem is that whether the variable is initialized. If this is the case then check for default values, which can be either "null" or "0". If the result is TRUE then you can display the message and if not then perform your task.

    Code:
    if (VARIABLE != "" || VARIABLE != null) {  
    // CODE HERE  
    }

Similar Threads

  1. Check if URL exists (Java)
    By Kelvin Little in forum Software Development
    Replies: 7
    Last Post: 08-01-2010, 04:04 PM
  2. How to check if file exists in directory with Php
    By Zool in forum Software Development
    Replies: 3
    Last Post: 03-11-2009, 12:36 PM
  3. Check if database or table exists
    By Xan in forum Software Development
    Replies: 2
    Last Post: 29-05-2009, 04:53 PM
  4. Powershell: To check a directory exists or not?
    By Chandrakant81 in forum Software Development
    Replies: 3
    Last Post: 18-02-2009, 06:26 PM
  5. How to Check File Exists or Not in Linux
    By Ettan in forum Software Development
    Replies: 0
    Last Post: 19-12-2008, 01:42 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,713,924,078.23104 seconds with 17 queries