DEV Community

bronxsystem
bronxsystem

Posted on

C# basic indexer question

Learning C# and this is bit embarrassing but I wanted to make sure I understand everything and not skip over things I do not understand.

is the line with the following code initializing "Roles" as a property on an instance of the Employee Class?

 public Employee() => Roles = new ProjectRoles(); 

        class ProjectRoles
        {
            readonly Dictionary<int, string> roles = new Dictionary<int, string>();
            public string this[int projectId]
            {
                get
                {
                    if (!roles.TryGetValue(projectId, out string role))
                        throw new Exception("Project ID not found!");

                    return role;
                }

                set
                {
                    roles[projectId] = value;
                }
            }
        }

        class Employee { 
            public int EmployeeId { get; set; } 
            public string FirstName { get; set; } 
            public string LastName { get; set; } 
            public ProjectRoles Roles { get; private set; } 
            public Employee() => Roles = new ProjectRoles(); 
}

    }

Probably painfully obvious to you but I just wanted to confirm thank you.

Top comments (2)

Collapse
 
pbeckerr profile image
PBeckerr • Edited

Its shorthand for a constructor, => can be used if you only have a single line of code in your block, but frankly i avoid it because for many it looks unfamiliar and you trade IMO space for lesser readability

this is the same in standard {} style

public Employee()
{
this.Roles = new ProjectRoles();
}

Collapse
 
bronxsystem profile image
bronxsystem • Edited

ohhhhh thank you very much sir. Turned light bulk on in my head.