-2

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

mason
  • 31,774
  • 10
  • 77
  • 121
JNA
  • 45
  • 9
  • 2
    There's no difference. It's private implicitly since you didn't declare an access modifier. See [Default Visibility for C#](http://stackoverflow.com/questions/3763612/default-visibility-for-c-sharp-classes-and-members-fields-methods-etc). – mason May 01 '17 at 18:40
  • Flip to the next page in whatever resource you're using to learn the language. That's where it tells you. – Anthony Pegram May 01 '17 at 18:44

2 Answers2

2

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

This will be marked as a duplicate but I'll answer anyway.

Both of these are instance variables of the class you're defining. They will only exist in memory when an instance of this class is created.

There is no difference between these two variables. By default, class/struct members without access modifiers are private, explicitly saying one is private and not using a modifier are equivalent, but it is best practice to always specify the access that should be allowed for your members/methods

RH6
  • 144
  • 8
  • "By default, attributes without access modifiers are private" -- 1) Should use the term "member" instead of "attribute" as the MSDN does; attributes are a different thing in c# entirely, 2) Reading [here](https://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx), only class and struct members default to `private`, but your answer doesn't clearly state this which could lead to problems. – Quantic May 01 '17 at 18:48
  • @Quantic Edited for clarity. He wasn't referencing enums or interfaces so I didn't think I needed to be specific. – RH6 May 01 '17 at 18:53