Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static property in c# 6

Tags:

I'm writing a small code to more understand about property and static property. Like these:

class UserIdentity {     public static IDictionary<string, DateTime> OnlineUsers { get; set; }     public UserIdentity()     {         OnlineUsers = new Dictionary<string, DateTime>();     } } 

or

class UserIdentity {     public IDictionary<string, DateTime> OnlineUsers { get; }     public UserIdentity()     {         OnlineUsers = new Dictionary<string, DateTime>();     } } 

Since I changed it to:

class UserIdentity {     public static IDictionary<string, DateTime> OnlineUsers { get; }     public UserIdentity()     {         OnlineUsers = new Dictionary<string, DateTime>();     } } 

it gave me error message:

Property or indexer 'UserIdentity.OnlineUsers' cannot be assigned to -- it is read only

I knew the property OnlineUsers was read only, but in C# 6, I can assign it via constructor. So, what am I missing?

like image 748
Tân Avatar asked Jul 03 '16 14:07

Tân


1 Answers

You're trying to assign to a read only static property in an instance constructor. That would cause it to be assigned every time a new instance is created, which would mean it's not read only. You need to assign to it in the static constructor:

public static IDictionary<string, DateTime> OnlineUsers { get; }  static UserIdentity() {     OnlineUsers = new Dictionary<string, DateTime>(); } 

Or you can just do it inline:

public static IDictionary<string, DateTime> OnlineUsers { get; } = new Dictionary<string, DateTime>(); 
like image 185
Matti Virkkunen Avatar answered Oct 03 '22 23:10

Matti Virkkunen