C# private, static, and readonly

ant2009 picture ant2009 · Jun 9, 2009 · Viewed 11k times · Source

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,

Answer

victor hugo picture victor hugo · Jun 9, 2009
  • 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.