WhatsThePoint WhatsThePoint - 4 months ago 139
C# Question

object initialization can be simplified

With my code I get 3 messages all saying

object initialization can be simplified
and in my ever growing thirst for knowledge (and my OCD) I would like to "fix" my code so that these messages dont appear. I know I can just set it so these messages dont appear but I will still have in my head that they are there in the background which doesnt sit right with me. If anyone can point out how to "simplify the initialisation" that would be great so I can improve my skills. If more code is required let me know and I can add it in.

1st:

TreeNode node = new TreeNode(drive.Substring(0, 1), driveImage, driveImage);//issue on this line
node.Tag = drive;


2nd:

DirectoryInfo di = new DirectoryInfo(dir);
TreeNode node = new TreeNode(di.Name, 0, 1); //this line


I suspect with the treenodes its because I have given them the same name but I tried changing the name but it didn't make a difference.

3rd:

OleDbCommand select = new OleDbCommand();//this line
select.Connection = cnDTC;
select.CommandText = string.Format("SELECT MAX(VERSION_NO) AS MAX_VERSION FROM ({0})", strSQL2);

Answer Source

1st:

var node = new TreeNode(drive.Substring(0, 1), driveImage, driveImage) {
    Tag = drive
};

2nd:

var node = new TreeNode(new DirectoryInfo(dir), 0, 1);

3rd:

var select = new OleDbCommand(string.Format("SELECT MAX(VERSION_NO) AS MAX_VERSION FROM ({0})", strSQL2), cnDTC);

BTW: whenever this kind of message appears, try putting the cursor on that line and hit "Ctrl+." (or click the appearing lightbulb) - which opens up "quick-Fix / quick-refactor"

further read on var (it really is not evil ;) ) and some more documentation about object- and collection-initializers