Go Back   TechArena Community > Software > Software Development
Become a Member!
Forgot your username/password?
Tags Active Topics RSS Search Mark Forums Read

Reply
 
Thread Tools Search this Thread
  #1  
Old 28-08-2009
Member
 
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?
Reply With Quote
  #2  
Old 28-08-2009
Member
 
Join Date: May 2008
Posts: 2,008
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
}
Reply With Quote
  #3  
Old 28-08-2009
Member
 
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
}
Reply With Quote
  #4  
Old 28-08-2009
Member
 
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  
}
Reply With Quote
Reply

  TechArena Community > Software > Software Development
Tags: ,



Thread Tools Search this Thread
Search this Thread:

Advanced Search


Similar Threads for: "How to check if variable exists in C#"
Thread Thread Starter Forum Replies Last Post
Check if URL exists (Java) Kelvin Little Software Development 7 08-01-2010 04:04 PM
How to check if file exists in directory with Php Zool Software Development 3 03-11-2009 12:36 PM
Check if database or table exists Xan Software Development 2 29-05-2009 04:53 PM
Powershell: To check a directory exists or not? Chandrakant81 Software Development 3 18-02-2009 06:26 PM
How to Check File Exists or Not in Linux Ettan Software Development 0 19-12-2008 01:42 PM


All times are GMT +5.5. The time now is 02:38 AM.