Initializing to null at declaration vs using conditional [closed]

I'm aware that premature optimization is the root of all evil but I'm going to ask this anyway.

Say I have this:

string foo = null;
if (IsBar) {
    foo = "...";
    // something else
}

But I think I read somewhere long time ago that giving a value to a variable will be slightly slower. Hence, I am contemplating on doing this:

string foo;
if (!IsBar) {
    foo = null;
} else {
    foo = "...";
    // something else
}

May I ask which is the best practice?


It has really nothing to do with performance, but there's a difference anyway.

If you assign a value you lose the capability that VS or resharper help you to determine if the variable gets intialized in one of the branches, that could help you to find a logical bug in your code. So that might be a disadvantage. But as you can see in your sample it's getting a little bit more verbose if you don't assign null.

It depends on the actual case if you should prefer one over the other.


I would do something like this:

string foo = IsBar ? "..." : null;