Mavershang
Mavershang

Reputation: 1278

How to check whether a variable or an array is initialized in 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.

Upvotes: 8

Views: 13287

Answers (6)

Donnie
Donnie

Reputation: 46943

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.

Upvotes: 1

Roast
Roast

Reputation: 1755

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.

Upvotes: 2

Farmer
Farmer

Reputation: 11003

Try This, :

If var = NULL Then
MsgBox ('Not initialized')
End If

Upvotes: 1

John Weldon
John Weldon

Reputation: 40799

tongue in cheek, but accurate answer

Scan your source code and find all usages and declarations of the variable to verify that it is initialized either at declaration, or else somewhere guaranteed before using it.

Upvotes: 0

Adam Robinson
Adam Robinson

Reputation: 185703

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.

Upvotes: 7

tster
tster

Reputation: 18257

No. However, you will have a compiler error if it is a local variable. If it is a class member then it is automatically initialized to the default (0 for ints, null for objects, etc.)

Upvotes: 0

Related Questions