(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)
public class Foo
{
public int Bar { get; private set; }
}
Omitting the word 'private' would change the accessibility.
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".
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!
In C# version 7.2 and later.
The private protected keyword combination is a member access modifier. A private protected member is accessible by types derived from the containing class, but only within its containing assembly.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private-protected
Related
C# 7.2 introduces the private protected modifier.
I've always protected access to fields with properties, allowing access via the Get/Set methods as I typically don't want the internal state of my object modified by anything other than my own class.
I'm trying to understand why the C# language team have added this feature. After an extensive search on google, and reading and watching the 'what's new' media (I've watched the press release, details and video by Mads Torgerson), I am still none the wiser.
To me, this appears to allow a developer to break the Liskov Substitution principle, but this may be because I do not understand why this feature now exists.
I understand how it can be used, just not why - please can someone provide a real-world usage example rather than the contrived one in the MSDN documents?
Before C# 7.2 we had protected internal modifier. This really means protected OR internal, that is - member A is accessible to child classes and also to any class in the current assembly, even if that class is not child of class A (so restriction implied by "protected" is relaxed).
private protected really means protected AND internal. That is - member is accessible only to child classes which are in the same assembly, but not to child classes which are outside assembly (so restriction implied by "protected" is narrowed - becomes even more restrictive). That is useful if you build hierarchy of classes in your assembly and do not want any child classes from other assemblies to access certain parts of that hierarchy.
We can take example that Jon Skeet provided in comments. Suppose you have class
public class MyClass {
}
And you want to be able to inherit from it only in current assembly, but do not want to allow to instantiate this class directly except from within this class hierarchy.
Inheriting only within the current assembly may be achieved with internal constructor
public class MyClass {
internal MyClass() {
}
}
Preventing direct instantiation except withing current class hierarchy may be achieved with protected constructor:
public class MyClass {
protected MyClass() {
}
}
And to get both - you need private protected constructor:
public class MyClass {
private protected MyClass() {
}
}
For two-word access modifiers I have this concept - the first accessor is related to another assembly, the second one to that assembly in which it was defined.
protected internal
protected in another assembly: accessible only in the child classes.
internal in the current assembly: accessible by everyone in the current assembly.
private protected
private in another assembly: is not accessible.
protected in the current assembly: accessible only in the child classes.
Lets suppose that you have an internal class called SomeHelper that you want to use as part of the implementation of a public abstract base class:
public abstract class Test
{
// Won't compile because SomeHelper is internal.
protected SomeHelper CreateHelper()
{
return new SomeHelper();
}
public int Func(int x)
{
var helper = CreateHelper();
return helper.DoSomething(x);
}
}
internal class SomeHelper
{
public virtual int DoSomething(int x)
{
return -x;
}
}
This won't compile because you cannot have a protected method returning an internal type. Your only recourse is to not use SomeHelper in that way, or to make SomeHelper public.
(You could make SomeHelper a protected inner class of Test, but that's not going to work if SomeHelper is intended for use by other classes that don't derive from the base class.)
With the introduction of the private protected feature, you can declare CreateHelper() like so:
private protected SomeHelper CreateHelper()
{
return new SomeHelper();
}
Now it will compile, and you don't have to expose your internals.
protected internal
implies to "protected or internal" - any type/member defined with this access modifier can be accessed in the following scenarios - (A) in the same assembly, (B) class which is defined in another assembly and derives from the container class
private protected
implies to "protected and internal" - any type/member defined with this access modifier can be accessed in the following scenario - class that inherits from the container class and belongs to the same assembly
I'm not entirely sure about this. Is it 'static'?
The keyword you're looking for is partial.
https://msdn.microsoft.com/en-us/library/wa80x488.aspx
Yes partial is needed, but you also need abstract on the methods and the classes or it still won't compile because non-abstract methods must declare a body.
No It's not static. You need Partial Class. Also You need to provide body to your functions.
It is possible to split the definition of a class or a struct, an
interface or a method over two or more source files. Each source file
contains a section of the type or method definition, and all parts are
combined when the application is compiled.
To split a class definition, use the partial keyword modifier.
See Below example:
public partial class Employee
{
public void DoWork()
{
}
}
public partial class Employee
{
public void GoToLunch()
{
}
}
I really like declaring all of my methods at the start of a class and would like to do so with forward declarations and then implement them further down. Is this possible in C#?
Ex:
private void Test();
private void Test()
{
}
Yes you can do this. Or you can kinda sorta do this. But for each of these possible "Solutions", if it is for cosmetic reasons only don't use these constructs.
One trick is to use a partial class with partial methods.
partial class A
{
partial void OnSomethingHappened(string s);
}
// This part can be in a separate file.
partial class A
{
/* Comment out this method and the program
will still compile.*/
partial void OnSomethingHappened(string s)
{
Console.WriteLine("Something happened: {0}", s);
}
}
As highlighted in the referenced documentation, its uses are limited:
A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not. If the developer does not supply an implementation, the compiler removes the signature at compile time.
The following conditions apply to partial methods:
Signatures in both parts of the partial type must match.
The method must return void.
No access modifiers are allowed. Partial methods are implicitly private.
As pointed out in #Serv and #StanimirYakimov answers, another "kinda sorta" construct that can be used is the declaration of an interface or pure abstract class, very similar to how you would declare one in c++:
public interface IA
{
int GetTheOneAndOnlyNumber();
}
public abstract class AA
{
protected abstract void OnSomethingHappened(string s);
}
public class A : AA, IA
{
public int GetTheOneAndOnlyNumber()
{
return 42;
}
protected override void OnSomethingHappened(string s)
{
Console.WriteLine(s);
}
}
When switching from a language we know well to a new language, there are always specific idioms and constructs that we will miss. This does not mean that it is wise to try to emulate them with non-idiomatic constructs in the new language.
If you would like to have a condensed view of the structure of your code in Visual Studio, there are several standard ways of doing that, such as the Object Browser and Class View.
And if you search and look around, you will find other available tools that can help you with getting a quick overview of the structure of your code.
You can do it using interfaces
Just define which methods your class will use by inheriting from an interface.
See this interface as a mixture of forward declarations and a contract. Classes inherting from an interface must implement all of its members.
public interface iSomeClass
{
void MyMethod1();
bool MyBoolMethod();
}
public class MyClass : iSomeClass
{
public void MyMethod1()
{
//...
}
public bool MyBoolMethod()
{
//...
return true;
}
}
Simple answer no it is not possible.
The reason is that there are no standalone functions in C# but classes with methods.
Also in other languages like C++ once you start using classes forward declaration of the methods themselves are not needed. It can be that the classes themselves need forward declarations in C++ but since you are talking about methods the comparison still stands.
Bottom line a class is completely defined by its methods in any order they are defined.
You can't really do things like this in C#. I am not sure why you would really want to anyway. Having the declaration and definition in one place is simple and easier to understand
Doing something like this is required in some other languages, but forcing that pattern in C# probably isn't a good idea.
No you can not do it. You can only declare abstract methods like this. Otherwise it will give you an error.
I tried and it gave me
Error 1 'Project.SomeClass.ABC()' must declare a body because it is not marked abstract, extern, or partial
Only abstract methods can be defined like this, abstract methods need only a prototype to be overridden.
This is valid:
public abstract void ABC();
Forward declaration is not possible in C# classes. It's possible only in Interfaces and if your method is abstract. Something like this is allowed
abstract void Draw();
protected internal class foo
{
//this compiles without any errors
}
also
internal class bar
{
public int quix;
protected internal int zyx;
//this compiles without any errors
}
Are these compiler bugs or my misinterpretation of the standard?
Explanation:
Classes can't have protected internal access modifier, only public or internal according to MSDN (Classes and structs that are declared directly within a namespace (in other words, that are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified).
Not all access modifiers can be used by all types or members in all contexts, and in some cases the accessibility of a type member is constrained by the accessibility of its containing type (MSDN). Public should fail. Protected internal is ambiguous for me - internal modifier is not necessary.
Edit: The fact that I'm using Mono is unnecessary cause the question was about what standard says and not what MONO does or does not. Maybe I'm coding my own compiler. That's why I quoted MSDN to be precise what is allowed and what is not.
As mentioned in my comment above, protected internal means protected or internal NOT protected and internal. No bug here :)
Further information/explanation is on haacked
In response to your questions:
A class within a namespace (and not within another class) can only be declared as public or internal. HOWEVER, a class within another class can be declared as protected internal, private, etc.
Yes, protected internal can be used inside a class whose access modifier is more strict than it's members, see example of a perfectly valid usage below (note that the class is inside the Program class):
public class Program
{
static void Main(string[] args)
{
}
private class Foo
{
private int priv { get; set; }
protected internal int protint { get; set; }
public int pub { get; set; }
}
}
From Access Modifiers (C# Programming Guide)
protected internal
The type or member can be accessed by any code in the assembly in
which it is declared, or from within a derived class in another
assembly.
To quote the MSDN entry on this:
protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.
So the declaration makes perfect sense, it's just working differently as expected when used outside a class.
In addition, I really doubt that the "protected and internal class" would ever compile if the class was declared as a member of some namespace:
C# compiler said:
Elements defined in a namespace cannot be explicitly declared as
private, protected, or protected internal
Protected classes will be always nested classes!
UPDATE
Since you're trying your code sample in some version of Mono compiler, and you said in your sample code in your question //this compiles without any errors, I couldn't understand why you didn't tagged the question for Mono.
The standard is the Microsoft C# compiler behavior. If you ask a question about "why something compiles" and you don't mention that you're not using the official one, you're just making the assumption that any compiler would compile your code.
Do you want to know which is the standard? It's -again-: Protected classes will be always nested classes!
Keyword protected belongs to inheritance and keyword internal belongs to scope.
Assume i have a class:
public class Products
{
public string ID { get; set; }
public string Name { get; set; }
public string GetItemName() { ... }
public void SetItemName() { ... }
public string GetItemID() { ... }
public void SetItemID() { ... }
//...
}
It is any way to make all the properties or method inherits the parent class's access modifiers,so i don't have to assign [public] to each of properties/method.
public string Name { get; set; }
public string GetItemName() { ... }
public void SetItemName() { ... }
That's not C# code, that's C++. A language that doesn't support properties, but does support this:
public:
string GetItemName();
void SetItemName();
Which is probably what you are really asking for. No, never make the mistake of comparing C# to C++, it resembles the language only in passing. The accessor keyword must be applied to every member. Good thing is, you'll have a lot less of them. Delete the GetItemName and SetItemName methods, the Name property is all you need.
Here's an old magazine article that might be useful to you, "C++ -> C#: What You Need to Know to Move from C++ to C#"
There is no way to do this with class. It's how C# syntax is defined. If you skip access modifier then the default value is applied, for classes it would be internal modifier and for their members private.
Other default values according to specification are:
Interfaces, like classes, can be declared as public or internal types. Unlike classes, interfaces default to internal access. Interface members are always public, and no access modifiers can be applied.
Namespaces and enumeration members are always public, and no access modifiers can be applied.
Delegates have internal access by default.
Any types declared within a namespace or at the top level of a compilation unit (for example, not within a namespace, class, or struct) are internal by default, but can be made public.
No, the language specs say that if you don't specify the access modifier, a default one will be used:
Members in classes and structs are private by default.
Types (classes, structs, delegates, interfaces and enums) are internal by default, unless they are placed within another type (nested classes) when they default to private..
Interface members, enum members and namespaces have no concept of accessibility modifiers, but can be thought of as always being public.