Prisoner ZERO
Prisoner ZERO

Reputation: 14166

Is it better to declare a "private" field as private or as internal?

Is it better to declare a property as private or as internal? And...why is one preferred over the other?

Someone I work with declares "private" fields as internal all the time and I see no point to it...so I must be missing something.

EXAMPLE:

/// Someone I work with does this
public class SomeClass
{
    internal Document _document;
    internal Contractor _contractor;
    internal IUser _user;
    internal Project _project;
}

/// I usually do this
public class SomeClass
{
    private Document _document;
    private Contractor _contractor;
    private IUser _user;
    private Project _project;
}

Upvotes: 2

Views: 964

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500055

Usually a purely private automatically implemented property might as well be a private field.

As a brief rule of thumb, restrict everything as much as you can without causing too much pain. If nothing else in your assembly uses those properties (or should reasonably use those properties), then making them private (and possibly making them plain fields) is a good approach.

EDIT: Okay, now that we're talking about fields, definitely, definitely make them private. Non-private fields should be incredibly rare - pretty much the only use I can think of would be constants (whether actually const or just readonly static fields of an immutable type). Even then I'd normally use properties. Just occasionally for games and other performance-critical situations, it's worth breaking the rules - but you need to understand and respect those rules first.

Fields are an implementation detail - exactly how you store the data within an object shouldn't be interesting to other code trying to use that object. Focus on the difference between the API that a type should support and the implementation of that API.

Upvotes: 4

JaredPar
JaredPar

Reputation: 754575

A field, and any other member, should be declared with most restrictive access modifier that allows the member to be used as needed.

  • internal will only allow it to be used from within the same assembly or friend assemblies
  • private will only allow it to be used from within the type itself

Whichever of these satisfies your scenarios is the one that should be chosen.

I'm guessing though that private is more appropriate here. Given the field name is not compliant with the .Net Design Guidelines it seems like it's meant to be private to the type. Hence I would make it private or give it an appropriate name.

Upvotes: 11

tjg184
tjg184

Reputation: 4676

This depends on your requirement I suppose. If you need other classes to have access to the variables in the same assembly, then internal is the way to go. If you don't need other classes to have access, then declare them as private.

More can be found about internal here:

Practical uses for the "internal" keyword in C#

Upvotes: 2

Related Questions