in c# are methods private by default? - c#

If I have a method that does not specify its Accessibility Level will it be Private by default?
void Item_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
throw new NotImplementedException();
}
Is the above method private?

It is. The general rule if you don't define any modifier is "the most restricted modifier that can be applied here is used", so private for methods, internal for top-level classes, etc.

Yes, it is private.

For a method inside a class, default is private. It does vary based on the scope of where things are declared, here's an MSDN link with more specifics

Yes, for methods, like your example.
Class and struct members, including nested classes and structs, have
private access by default.
But that is not correct for all the access modifiers:
Classes, records, and structs declared directly within a namespace (in
other words, that aren't nested within other classes or structs) can
be either public or internal. internal is the default if no access
modifier is specified.
I consider this a good idea, because by default in OO, everything should be private and only what is really needed should be marked public.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers

Related

When I declare a class as internal, why does the IL show it as private?

If I declare a class as internal, why does the IL show it as private?
internal class Thing
.class private auto ansi beforefieldinit Thing.Thing
extends [mscorlib]System.Object
From IL's point of view, private means private to the assembly, i.e. internal in C#.
In C#, it is not possible to mark types as private if they are not nested. IL's equivalent accessibility for such types is nested private.
So we have:
C#'s internal -> IL's private (to the assembly)
C#'s private -> IL's nested private (to the enclosing type)
On MSDN, it says:
The C# keywords protected and internal have no meaning in IL and are
not used in the reflection APIs. The corresponding terms in IL are
Family and Assembly. To identify an internal method using reflection,
use the IsAssembly property. To identify a protected internal method,
use the IsFamilyOrAssembly.
So I guess it just makes them private, since they can't be accessed from elsewhere.
EDIT: I see how my answer might not be completely correct, I just thought it was something worth noting. The MSDN article I linked has some interesting stuff on this "what code we write" - "what it becomes" relationship.
The mapping of C# keywords to IL keywords isn't always a logical one. Ecma-335, section II.23.1.15 shows what flags are valid for a type. You'll see that it only defines Public, NotPublic and a set of NestedXxx flags. Nothing similar to "internal". So your class is actually NotPublic, displayed as "private" in ildasm.
It is easy to see a side-effect of this: try this declaration in your C# code:
private class DoesNotWork {
}
You'll get:
error CS1527: Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal

How can I organise these structures?

I have a number of different structs like below (obviously a little more involved and complicated), and am wanting to access private variables and methods from within methods within ABC while making those same variables and methods invisible from outside of the class MyMainClass; I know I could work around this with Reflection, but I'd rather not go down that route. I'm sure somebody here has had a similar problem - how did you get around it?
public class MyMainClass {
public struct SStruct {
private ulong myInternalVar;
public ulong InternalVar{ get{ return myInternalVar; } }
}
public void ABC() {
SStruct val1=new SStruct();
val1.gElementID=101;
}
}
Since SStruct is declared nested within MyMainClass, the implication (at least whenever I see something like that) is that SStruct is intended to support MyMainClass, and not be used by outside classes. If that's the case, the easiest work-around to your problem is to declared the struct as private, and then make the private members public or internal. Now, other classes can't access the members (since they can't access the struct at all,) while MyMainClass can.
If you're actually using SStruct elsewhere, I would recommend declaring it outside of any other classes, so that it's clear it's meant to be used that way.
Finally, you should just avoid mutable value types in general. Create constructors that set the state you want, and then let the struct live out its life that way. If you need to "alter" it, then the methods that do so should return a newly created instance with the required state.
You could mark private fields as internal, so that fields won't be visible outside the assembly they reside.
You can not achieve what you want if the nested types need to be public. The closest solution to what you are pretending is creating an internal setter, this way it would not be available outside the assembly. Anyhow, I am not sure what you are trying to achieve and why.
My advice, with the little information availabe, would be to consider implementing your structs as immutable types (mutable structs are evil) and then overload the constructor to set the internal state. This will not resolve the problem you are facing, it's just a piece of advice on your general design.

ERROR: the accessibility modifier of the set accessor must be more restrictive than the property or indexer

i'm having a bit of confusion with property accessors.
I'd like to have an internal property with its set accessor only accessible to derived classes.
something like this
internal [internalClass] MyProperty
{
get {return _prop;}
protected set {_prop = value;}
}
when i do this the compiler complains.
MSDN, when discussing this particular error suggests changing the set access modifier to private
which is not where i want this to go.
it looks like Protected Internal should be an option here however using this modifier gives the same error
I have a feeling i'm missing some basic understanding of access modifiers.
thanks
Neither protected nor protected internal is more restrictive than internal. Both would let derived types from a different assembly access the setter but not the getter. protected internal gives access to the union of protected and internal, not the intersection. (There is an access level representing the intersection in the CLR, but it's not exposed by C#.)
You might be best off using a private setter and a protected SetMyProperty method which just calls the private setter, if that matches what you want to achieve.
Internal is more restrictive than protected. Internal makes the member limited to the current assembly, whereas protected is accessible to an arbitrary large number of descendants outside of your assembly.
If you intend for this property to be accessible to classes or descendants outside of your assembly, you'll need to lose the internal attribute on the property. If you intend for this property to be used only within your assembly, then make the property accessor internal.
Unfortunately, this means you have to give up protected on the accessor of internal properties. This is an irritation because even though the property is limited to clients within your assembly, that doesn't mean you really trust all those clients to use your property correctly. It makes sense when you are the only author running around in your assembly's source code, but I would much prefer to retain protected semantics on internal classes when there are hundreds of developers running around in the source code of one large assembly.
For whatever reason, the compiler seems to believe that an internal class is permitted to have derived classes in other assemblies. The protected field is then considered available to other assemblies, through the derived class (that is, the field has no concept on its own of its class's access modifier). The compiler error is to indicate that (even though you know it won't ever happen) the indicated field is overextending its access rights.

method without access modifier

Ok this is bugging me.. I know I've read it somewhere and google isn't helping.
What is the accessibility level of a method that does not specify an access modifier?
void Foo()
{
//code
}
I want to say internal but I'm not 100% sure.
The default accessibility for a type is internal, but the default accesibility of that type's members depends on the type.
Generally speaking, members of a class are private by default, where as members of a struct are public by default. This varies by language; default struct access modifiers for C++ are public, where as for C#, they are private.
Assuming this is a C# method, since you have the ".net" tag.
People need to differentiate between "member" accessibility and "class" accessibility.
The default accessibility of class members (including methods) in C# is private. See https://msdn.microsoft.com/en-us/library/ba0a1yw2(v=vs.140).aspx
The default accessibility of a class itself is internal.
Yes, internal is the default for classes, but private is the default for members.
For a class: Internal is the default if no access modifier is specified.
For a method: Private is the default if no access modifier is specified.
From The C# Programming Language, Third Edition by Anders Hejlsberg et al, section 10.3.5 ("Class Members - Access Modifiers") on page 434:
A class-member-declaration can have any one of the five possible kinds of declared accessibility (§3.5.1): public, protected internal, protected, internal, or private. Except for the protected internal combination, it is a compile-time error to specify more than one access modifier. When a class-member-declaration does not include any access modifiers, private is assumed. [Emphasis mine]
And then in section 11.2 ("Struct Members") on page 539:
Except for the differences noted in §11.3, the descriptions of class members provided in §10.3 through §10.14 apply to struct members as well.
Section 11.3 does not mention anything about access modifiers, so my reading of this implies that members of a struct without an access modifier are also private by default. This corresponds with what MSDN says and with my own experience.
Oh wait, there's one more thing ....
interface method declarations are of course public by definition. So the following implementation is public, without an explicit access modifier.
public class MyClass : IEqualityComparer<MyClass>
bool IEqualityComparer<MyClass>.Equals(MyClass x , MyClass y) {}
}
hope this clarifies all as per screenshot directly from MSDN
Class methods are private and sealed by default in .NET.
This means the method is only visible within the class and cannot be overridden by the inherited class.

Relevance of 'public' constructor in abstract class

Is there any relevance of a 'public' constructor in an abstract class?
I can not think of any possible way to use it, in that case shouldn't it be treated as error by compiler (C#, not sure if other languages allow that).
Sample Code:
internal abstract class Vehicle
{
public Vehicle()
{
}
}
The C# compiler allows this code to compile, while there is no way i can call this contructor from the outside world. It can be called from derived classes only.
So shouldn't it allow 'protected' and 'private' modifiers only.
Please comment.
There's no reason for a public constructor for an abstract class. I'd assume that the reason that the compiler doesn't complain is as simple that they just didn't spend time covering that since it really doesn't matter if it's public or protected.
Inside an abstract class, for an instance constructor, modifiers public, protected internal, and protected are all equivalent. Then internal is more strict than them, and private is the most strict access.
If all instance constructors are private, only classes nested inside the class in question can inherit from it.
Note: If no instance constructors are given for a non-static class, then the compiler will generate one by itself. That's a constructor taking zero arguments. If the class is abstract, that auto-generated constructor is protected. Otherwise it is public.
The only situation I can think of where it makes a difference if an instance constructor of an abstract class is public or protected, is when you use reflection. As an example, saying
ConstructorInfo[] ctors = typeof(Vehicle).GetConstructors();
will give an empty array if the sole constructor is protected, and a length-1 array if it's public. But of course there are overloads that specify BindingFlags, so this is not a problem, just something to remember if one uses reflection.
Dupe: there is another question on SO just like this: Abstract class constructor access modifier
The answers on that question come down to the same thing in the end: it does not really matter if you declare it protected or public.
Also there seems to be some discussion about it in literature (e.g. in Framework Design Guidelines). This is referenced in this blogpost: Good design or bad design of abstract class?
Yes, a public ctor on an abstract class is meaningless and a bit misleading as it will behave as protected in that only derived classes may call it.
A private ctor will have little meaning outside of interesting edge cases.
A protected ctor would make sense if required by derived classes.

Categories