Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); 
like image 1000
WhatsThePoint Avatar asked Apr 25 '17 09:04

WhatsThePoint


People also ask

What is object initialization?

An object initializer is an expression that describes the initialization of an Object . Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.

What is object initialization in C#?

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements.

How are Initializers executed in C#?

Initializers execute before the base class constructor for your type executes, and they are executed in the order in which the variables are declared in your class. Using initializers is the simplest way to avoid uninitialized variables in your types, but it's not perfect.


2 Answers

While all the previous suggestions are also good, I would add a third way. Turn off those warnings and ignore them. While I appreciate Microsoft's attempts to get everyone coding efficiently and neatly, this is not a good suggestion in my opinion and it actually produces difficult to read and edit code.

Firstly, this essentially turns object initialisation into a single line of code, and any errors are reported as such. If you had 20 bits of data being loaded into an object you would be presented with an error on the first line and not told which property has errored. Debugging will not help as you are shown the whole block of code as the error.

Secondly, if you in future need to expand out the code and add additional code for a specific property you would now need to do this in seperate code. This adds to fragmentation and separates related bits of code(Maybe, it's debatable).

Both of these issues might seem like very minor things, but the warning suggests a fix that is also a very minor thing. For the sake of bracketing your initialisation you've made your code harder to debug and modify. This is a bad trade off in my opinion.

You can disable the warning by right-clicking the warning and selecting "suppress", or Go to Tools > Options > Text Editor > C# > Code Style > General > Prefer Object Initializer > and set the warning to None, or set the Preference to No. settings to change preference for object initializers

like image 176
Tony Cheetham Avatar answered Sep 18 '22 08:09

Tony Cheetham


1st

Before:

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

After:

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

2nd

Before:

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

After:

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

3rd

Before:

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

After:

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

3rd (with string interpolation):

var select = new OleDbCommand($"SELECT MAX(VERSION_NO) AS MAX_VERSION FROM ({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

like image 21
earloc Avatar answered Sep 22 '22 08:09

earloc