WhatsThePoint WhatsThePoint - 11 months ago 245
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.


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


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.


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


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


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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download