DEV Community

bronxsystem
bronxsystem

Posted on

1

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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay