Hello everyone,
can someone help me to understand the difference between the below code:
1. protected static PortalParametersContext Context { get; } = new PortalParametersContext();
2. protected static PortalParametersContext Context = new PortalParametersContext();
where PortalParametersContext is class.
Thanks

Amit MohantyPosted Jul 6, 2023, 12:50 PM
In the above code, Context uses a field initializer to initialize the property with a new instance of the PortalParametersContext class. The get accessor allows you to retrieve the value of the property, but since the set accessor is not defined, the property is read-only.
In this code, Context initialized directly with a new instance of the PortalParametersContext class. Unlike the property in the first code snippet, this is not a property but a field. Fields are typically used to store data directly, while properties provide a way to encapsulate data and control access to it.
In summary the main difference between the two code snippets is that the first one uses a property with a field initializer to provide read-only access to an instance of PortalParametersContext, while the second one directly initializes a field with an instance of PortalParametersContext.
Ramesh PalanivelPosted Jul 6, 2023, 10:43 AM
Hi Munish,
The difference on this methods are,
protected static PortalParametersContext Context { get; } = new PortalParametersContext(); - You can only create instance here.
protected static PortalParametersContext Context = new PortalParametersContext(); - You can initialize instance everywhere