0

I am from Java springboot world and recently started learning C# 10 (.NET 6) for one of our clients requirement, initially I was facing a lot of pain understanding fundaments of C# 10, but now I am little comfortable, however I am not able to find good documentation, blogs or questions which provides comparison between similar features and some useful example.

I am currently trying to understand the difference between below, please also check if below is valid ?

public class Employee {
  public int Id {get;}; 
  public string Dept {get; set;};   
  public string FirstName {get; readonly set;}; 
  public string LastName {get; private set;}; 
  public string DateOfJoining {get; init;};
}

This is my guess, please review and help me understanding

public class Employee {
  public int Id {get;}; // hardcoded must be defined at the design time and can never change?
  public string Dept {get; set;};   //mutable - can be modified multiple times?
  public string FirstName {get; readonly set;}; // NOT SURE 
  public string LastName {get; private set;}; // NOT SURE 
  public string DateOfJoining {get; init;}; //immutable - can be set only once from constructor? 
}

1 Answers1

0

First of all, there should not be a semicolon after the properties declaration.

this public string FirstName { get; readonly set; } is invalid, it will give compilation error. this test.Id = 1; will give compilation error as its readonly.

this test.Dept = "CS"; is allowed.

this test.LastName = "John"; is also not allowed, it will say set accessor not accessible.

this is allowed for init, not the one you have mentioned in your code.

public Test()
{
    DateOfJoining = "Today";
}

My class

internal class Test
{
    public int Id { get; }
    public string Dept { get; set; }
    //public string FirstName { get; readonly set; }
    public string LastName { get; private set; }
    public string DateOfJoining { get; init; }

    public Test()
    {
        DateOfJoining = "Today";
    }

}

check this also for the difference between init and readonly. Init is to allow assignment in object initialization as well online the readonly.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197