Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# need the private keyword?

(inspired by this comment)

Is there ever a situation in which you need to use the private keyword?
(In other words, a situation in which omitting the keyword would result in different behavior)

like image 621
SLaks Avatar asked Jun 14 '11 19:06

SLaks


People also ask

Does C have do-while?

The C do while statement creates a structured loop that executes as long as a specified condition is true at the end of each pass through the loop.

Does hep C go away?

It is highly curable ... Direct-acting antiviral medications — given over a 12-week period — actually can cure early acute hepatitis C better than 90% of the time.

What is || in C programming?

Logical OR operator: || The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool .


3 Answers

public class Foo
{
    public int Bar { get; private set; }
}

Omitting the word 'private' would change the accessibility.

like image 144
David Yaw Avatar answered Oct 23 '22 01:10

David Yaw


a situation in which omitting the keyword [private] would result in different behavior

David Yaw's answer gave the most usual situation. Here is another one:

In Account_generated.cs:

// Generated file. Do not edit!

public partial class Account
{
  ...

  private partial class Helper
  {
    ...
  }

  ...
}

In AccountHandCoded.cs:

public partial class Account
{
  ...

  public partial class Helper
  {
    ...
  }

  ...
}

The above code will not compile. The first "part" of Account requires the nested class Helper to be private. Therefore the attempt by the hand-coder to make Helper public must fail!

However, had the first part of the class simply omitted the private keyword, all would compile.

So for partial classes (and structs, interfaces), the access-level-free declaration

partial class Name

means "the other 'parts' of this class are allowed to decide what the accessibility should be".

Whereas explicitly giving the default accessibility (which is internal for non-nested types and private for nested ones) means "this class must have the most restricted access possible, and the other 'parts' cannot change that fact".

like image 35
Jeppe Stig Nielsen Avatar answered Oct 23 '22 01:10

Jeppe Stig Nielsen


private isn't about the runtime behaviour. It's to make your application maintainable. What's hidden by private can only ever affect the code outside its class through the public or protected members.

So the answer is 'no' for runtime behaviour, 'yes' for developer behaviour!

like image 1
Pontus Gagge Avatar answered Oct 23 '22 00:10

Pontus Gagge