Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a variable or an array is initialized in C#

Tags:

c#

My question is: can I check whether a variable (string or int/double type) or an array (string or int/double type) is initialized in C#?

Thanks in advance.

like image 255
Mavershang Avatar asked Jul 06 '10 18:07

Mavershang


4 Answers

You are guaranteed some sort of initialization. For any static or instance members, all variables are automatically initialized when the type or instance is constructed, either explicitly or implicitly (in which case default(Type) is the value, so 0 for numeric types, null for strings and other reference types, etc.).

For local variables, they cannot be used before declaration, so if you can check it, it's been initialized.

like image 178
Adam Robinson Avatar answered Oct 17 '22 03:10

Adam Robinson


Yes you can.

For types that require instances (string or arrays, as you asked), you can verify if they are null.

You could do this many ways but one way is :

if (myObject == null)
{
    //initialize it here
}

Primitive data types do not require instancing. For example:

int i;

wont be equal to null, it will be equal to 0.

like image 30
Roast Avatar answered Oct 17 '22 03:10

Roast


Try This, :

If var = NULL Then
MsgBox ('Not initialized')
End If
like image 1
Wassim AZIRAR Avatar answered Oct 17 '22 03:10

Wassim AZIRAR


C# requires that all variables be initialized to some value before you read them.

The code block:

int i;
if(i == 0)
{
  // something...
}

Will generate a compile-time error because you're trying to access the value of i before assigning it. This also applies to objects (although you can initialize them to null to begin with).

If you are wanting to know if you have modified from your initial assignment, then no, there is no way of telling that directly unless the initial assignment is to a sentinel value that will not be repeated by a subsequent assignment. If this is not the case you will need an extra bool to track.

like image 1
Donnie Avatar answered Oct 17 '22 02:10

Donnie