Writing to an accessory read-only C #

I am trying to do something similar to ASP.NET User.Identity.Name. I already made a class for storing information, but I do not know how to write a variable, since I just added get {};

private static string _firstName; public static string FirstName { get { return _firstName; } } 
+4
source share
3 answers

There are two ways to do this. The first way is to add a private setter.

 private static string _firstName; public static string FirstName { get { return _firstName; } private set { _firstName = value; } } 

Another option is to add a parameter to your constructor and set the value inside it.

 public YourClass(string firstName) { _firstName = firstName; } 
+3
source
 public class YourAwesomeClass { private static string _firstName; public static string FirstName { get { return _firstName; } } public YourAwesomeClass(string firstName) { _firstName=firstName; } } 

or if you use Dotnet 3.0 or higher, you can use the automatic property, Compiler will automatically create support fields for you.

 public class YourAwesomeClass { public static string FirstName { get;private set; } public YourAwesomeClass(string firstName) { FirstName=firstName; } } 
+2
source

Write a setter method:

 public static string FirstName { get { return _firstName; } set { _firstName = value; } } 
0
source

Source: https://habr.com/ru/post/1440200/


All Articles