Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object is defined?

Tags:

c#

I would like to check if an object is defined or exists using C#.

Something like this:

if (defined(Object)){

}
like image 245
Aka Avatar asked Mar 29 '10 12:03

Aka


People also ask

How do you check if an object is defined in JavaScript?

In a JavaScript program, the correct way to check if an object property is undefined is to use the typeof operator. If the value is not defined, typeof returns the 'undefined' string.

How do you know if an object is undefined or not?

Use the typeof operator to check if an object property is undefined, e.g. if (typeof obj. age === 'undefined') {} . The typeof operator will return the string "undefined" if the property doesn't exist on the object.

How do you know if a variable is defined?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.

How do I check if an object is defined in R?

Check if an Object of the Specified Name is Defined or not in R Programming – exists() Function. exists() function in R Programming Language is used to check if an object with the names specified in the argument of the function is defined or not. It returns TRUE if the object is found.


2 Answers

You check if it's null in C# like this:

if(MyObject != null) {
  //do something
}

If you want to check against default (tough to understand the question on the info given) check:

if(MyObject != default(MyObject)) {
 //do something
}
like image 135
Nick Craver Avatar answered Oct 10 '22 10:10

Nick Craver


If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.

If you have an instance, and you want to ensure it's not null, simply check for null:

if (value != null)
{
    // it's not null. 
}
like image 27
David Morton Avatar answered Oct 10 '22 12:10

David Morton