开发者

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 开发者_如何学JAVAadvance.


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.


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.


Try This, :

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


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.


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.)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜