Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# private, static, and readonly

Tags:

I was reviewing some code for log4net and I came across this.

private static readonly ILog logger = LogManager.GetLogger(typeof(AdminClient)); 

I am wondering why would you need to have private static readonly.

From my understanding private would mean that the variable cannot not be used outside the class unless there is a accessor method or get property.

static would mean that the variable is scoped only in this file only.

readonly would mean that you can only read from the value and cannot assign it.

So, I am thinking that the person who wrote this code. declared it private as they don't want it used outside the class and static so that don't want it used outside the file. However, if there is a get property would static prevent this form happening.

I think I can understand readonly and the value is only to be read from and not set.

Many thanks for any advice,

like image 363
ant2009 Avatar asked Jun 09 '09 04:06

ant2009


1 Answers

  • private No one should use the logger field outside the class (even in subclasses), if you don't set this any other class could use your logger for log in your class' name.
  • static The attribute is attached to the class so it won't repeat with each instance of the class. If you don't set this the logger attribute will occupy extra space in memory with every instance the system makes of the object (you misunderstood this).
  • readonly The logger field shouldn't be modified.
like image 122
victor hugo Avatar answered Sep 18 '22 17:09

victor hugo