0

The purpose of using ReadOnly collections is discussed here: Solution for CA2227 or better approach?

My question is if there is a way not to make the code "ugly" by using the new initializer of c#.

For example we have the following code

                return new User
                {
                    Firstname = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.UserFirstname)?.Value,
                    Lastname = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.UserLastname)?.Value,
                    LogonName = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.UserLogon)?.Value,
                    Roles = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.UserRoles)?.Value.Split(";#").ToList()
                };

When the model for Roles is

public List<string> Roles { get; } = new List<string>();

the above code won't work because we cannot assign a new List to Roles.

Is there a way to return new User without blowing up the code? Shure I could create an initializer method in the User class but this makes the new User(...) call cluttered

PascalTurbo
  • 2,189
  • 3
  • 24
  • 41
  • For clarity: is the collection read-only or is the property get-only? – ProgrammingLlama Jul 16 '21 at 06:58
  • When there are actual collections with `ReadOnly` in their name - [`ReadOnlyCollection`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.readonlycollection-1?view=net-5.0), it's best to avoid such capitalisation when you're not actually talking about those. As Llama says, this appears to be a read-only property. – Damien_The_Unbeliever Jul 16 '21 at 07:01
  • Thanks for the clearance. I've changed the title – PascalTurbo Jul 16 '21 at 07:04
  • 1
    You could make use of a public, static `FromClaims` method in the `User` class. Seems like all your properties are based on a `claim`. You'd still have to assign the values as above but only once and not every time you're creating a new `User`. – devsmn Jul 16 '21 at 07:06
  • 1
    `user.Roles.AddRange(claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.UserRoles)?.Value.Split(";#"));` ? – Marc Gravell Jul 16 '21 at 07:15

0 Answers0