Reputation: 6065
I'm sorry if this thread will be considered as subjective, but my question is more on the technical side.
I'm working with C# in the Framework .Net 4.0. I spent a few years playing with C++ and I've received an education where variables that were not initialized got me a kick in the butt.
Today, each time I see a uninitialized variable in a C# snippet, I do shiver a little bit and I really cannot make up my mind if I should initialize them or not.
I've read many articles where people say that, some are initialized, others not (members vs local), I've read articles where people say that initializing vars in C# gets you in trouble with performance...
In my current application, I want to have good performance but before all, I need to avoid having stupid bugs because of variables that are uninitialized.
What is the best practice regarding this ?
Edit :
public MyClass
{
private int foo; // Is it initialized ? Do I have to ?
public void MyMethod()
{
int bar; // Is it initialized ? Do I have to ?
...
}
} // Is it a good practice to initialize every vars all the time or not ?
// Will I get troubles by not initializing those ?
// If I do initialize them, will I get performance slowdown ?
Upvotes: 1
Views: 378
Reputation: 30097
I want to know, if, in C#, ALL variables are automatically initialized, or if there are some cases where there are not
When you declare a reference type variable like instance of SomeClass
, it's default value will be null
. Your variable will get initialized once you allocate some memory for it using new
SomeClass someClass; //not initialized, it's value is null
someClass = new SomeClass(); //initialized
On the other hand value types are initialized when you declare them. For example
int bar; //initialized with value 0
Is it a good practice to initialize every vars all the time or not ?
Well, it depends on scenario. For example when you declare a bool it's default value is false
. But for reader's understanding it's better to explicitly do bool myBool = false
. On the other hand if you have to pass a variable as out
to some method, initializing a variable is of no use because it is responsibility of method. It really depends on your scenario and practises you like to follow.
Will I get troubles by not initializing those ?
If you are fine with default value(uninitialized value) then you won't get in to trouble. But if your code expects some initialized value and your variable is not initialized then you might get into trouble.
If I do initialize them, will I get performance slowdown?
Nope. If your app's performance is really slow you should use some profiler to find out what is causing slow performance. Initializing variable is very unlikely to cause performance issue
Upvotes: 2
Reputation: 180917
In C# you won't have a problem with uninitialized variables having random values like you do in C/C++.
Some variables (fields/statics for example) are guaranteed to be initialized to their default value (generally null/0), and the compiler give you an error in all cases where a default value is not guaranteed and you've not manually initialized the variable before use.
In other words, if you're not sure, trust the compiler to tell you.
Edit: The reverse is also true, if you manually initialize your local variables in method to their default and the compiler can see that you never use it before changing it, it will remove the initialization for you, so no overhead unless you actually use the value.
Upvotes: 4
Reputation: 4075
Initializing or not initializing a variable in C# depends on what you want to achieve, and both options are valid in different situations.
Take, for example, a class that exposes some properties and you wish the properties to have a default value:
public class X
{
private object _propertyName;
public object PropertyName
{
get { return _propertyName; }
set
{
_propertyName = value;
doSomething();
}
}
}
In this class, leaving _propertyName
uninitialized may expose you to a NullReferenceException
if you try to read the value of the property before it has been set, so initializing it to a suitable default value is good practice here.
However, sometimes you want to provide the option for the user to pass in null
, in which case, initializing a variable may overwrite this legitimate input.
public void doSomethingToObjectInCollection(object key, List<object> haystack)
{
// First find it in the collection
object foundValue;
for( int i = 0; i < haystack.Count; i++ )
{
if( haystack[i].KeyField == key )
foundValue = key;
}
if( foundValue != null )
{
// Do something here if there was a foundValue
}
}
In this example, initializing foundValue to a default value will create incorrect behaviour. Of course, you can initialize it to null
explicitly if it is so hard for you to look at, but this doesn't change the behaviour of the code (unlike C++).
As for performance considerations, unfortunately there isn't a "yes it's bad" or "no it's OK" answer. In most applications it is probably not going to matter a great deal, but if you have hard performance requirements then deciding what to do requires a context-specific understanding of exactly what is going on when you do initialize a variable.
Value types will be initialized on allocation to zero, but this is hardly an expensive operation and so likely will not overly concern you.
Reference types are where you may incur a performance hit by initializing values before they are used. For instance:
public class TheClass
{
MyType x = new MyType();
public TheClass()
{
x = new MyType(/*some arguments*/);
}
}
This will result in two allocations for x, the first with the default constructor, the second inside the constructor with new values. This is because class level variables are initialized before the constructor.
Upvotes: 1