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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With