Search code examples
c#oopinstance-variables

In a class, what is the difference between instance variable and variable without modifier in c#


In the following code:

public class Foo
{
  private object first;  

  object second;

  public void Bar()
  {
    first = "1234";

    second = "1234";
  }
}

What is the difference between two declaration? I'm new to OOP and was wondering what would be the difference...

Thanks


Solution

  • What is the difference between two declaration?

    Nothing, as this is C#. In general, if you declare anything in C# without using access modifiers, it's equivalent to using the most private valid access modifier for that place1.

    So yes, declaring

    private object first;
    

    is equivalent to

    object first;
    

    Personally, I prefer being explicit about access modifiers - others prefer to be as terse as possible.


    1 The one exception to this is specifying an access modifier for part of a property. That has to be more private than the property itself; if you don't specify an access modifier there, it's implicitly the same access as the property itself.