The requested page is not available for the requested platform. You are viewing the content for Default platform.

Initializer can be used

CodeRush Classic shows the Initializer can be used code issue if an object creation statement is immediately followed by statements that assign values to object properties.

Fix

Convert the current instantiation and subsequent property assignments into an initializer statement.

Purpose

Highlights the object creation statements, which can be converted into initializer expressions because an initializer expression is more compact.

Example

public void AddUser(string name, string familyName, int birthYear)
{
    var user = new UserInfo();
    user.Name = name;
    user.FamilyName = familyName;
    user.BirthYear = birthYear;
    if (_Users == null)
        _Users = new List<UserInfo>();
    _Users.Add(user);
}

Fix:

public void AddUser(string name, string familyName, int birthYear)
{
    var user = new UserInfo(){ Name = name, FamilyName = familyName, BirthYear = birthYear };
    if (_Users == null)
        _Users = new List<UserInfo>();
    _Users.Add(user);
}