What is the default access specifier of Main method in C#?
If the default access specifier of static void Main() is private, then how does an external entity eg. OS invoke this method?
Any foreign process should not be able to call this method.
What is the default access specifier of Main method in C#?
The default access specifier of all methods is private.
Then how does an external entity such as the OS invoke this method?
It doesn't. The main method is invoked by the CLR. Since the CLR is the thing that is enforcing the semantics of privacy it can ignore it.
But that is not actually the right answer. The right answer is to say that your question reveals that you have a common but incorrect idea of what "private" applies to. "Private" does not mean "this method cannot be called from an external entity".
Rather, access modifiers apply to the name of the thing. That is, an access modifier determines the accessibility domain of the name of a thing: it determines the region of code in which the name could possibly mean the thing in question. The private modifier means "the accessibility domain of this entity is the entire body of the type in which it is declared". Any attempt to look up that name outside of that accessibility domain will not result in name resolution choosing the entity. Either name resolution will choose something else, or name resolution will fail.
It is absolutely possible to call a private method via some other mechanism. You can make a delegate to it and pass it around. You can use private reflection if you are sufficiently trusted. And so on. The invocation of the main method is just such a mechanism; it doesn't look up Main by name in the first place!
First, the OS knows nothing about your Main.
The CLR (which calls Main) can call it, no matter what access level you specified for it (internal, private, protected, public). You can even view and call/use all methods/types/interfaces from external libraries yourself using reflection (yes, internal and private, too).
Its default access specifier is private, although it also could be public or internal.
from msdn:
http://msdn.microsoft.com/zh-cn/library/acy3edy3
Further more, we wonder why the private method called by the external. I think that, access levels(public,internal,protected,private) defined in C# are just limited by compiler, it's a strict rule for IDE and developers, but to CLR and OS, they don't have to obey this rule, they can call any function or method from reflected address, like we could invoke method by reflecting, so the private Main method could be the entry.
Related
I've read around on the internet and I've heard people say
Access specifiers ::
The access specifier determines how
accessible the field is to code in
other classes. Access ranges from
totally accessible to totally
inaccessible. You can optionally
declare a field with an access
specifier keyword: public, private,
or protected.
Access Modifiers ::
You can optionally declare a field
with a modifier keyword: final or
volatile and/or static and/or
transient, abstract, etc.
Is there any difference at all? Because most definitions for access modifiers and access specifiers state the same thing.. which seems so ambiguous.
In this context, you can think of access specifiers as protection specifiers -- they specify where a variable can be accessed from. By contrast, access modifiers are completely different; they specify how variables should (or should not) be accessed; e.g. read-only, volatile, etc.
i.e., a variable can be public but read-only, or it can be private and writable -- the access specifiers have nothing to do with the modifiers.
However, I'm a little surprised that the terminology is for C#, since Microsoft actually calls public and private "access modifiers", and it calls volatile and readonly just plain "modifiers".
As far as I can see, there is no difference at all between the terms. The MS C++ documentation for example uses both terms for the same thing.
Refer from MSDN C# 4.0 document, I think you misunderstand something. C# does not has some word like "access specifier" but it call modifiers or access modifiers for modifiers that use to control access level.
Hope this help.
Update
I think, this question like you ask me that what difference between package and namespace is. It depends on what language or professor that you use or believe. Nothing is wrong on same kind like this question.
From experience (and the meaning of words), access modifier should mean about controlling access like public or private. In the other hand, Access Specifiers should be the super class of access modifier that mean it include other keyword like static, final, readonly or something like that in it.
PS. Both C#, VB.NET and Java, they use access modifier for keyword like public or private. In the other hand, C++ use access specifier for the same keyword.
Modifiers (C# 4.0)
Access Levels in Visual Basic (VB.NET 2010)
Controlling Access to Members of a Class (Java)
Access Specifiers (C++ 2010)
I believe an access specifier determines the visibility for a certain field / method.
An access modifier tells you more about the behavior and use of that field. You can say whether or not the field requires an instantiated object or if it can be overriden.
Access specifiers of a class indicates what other class variables can access in the present class.
Access modifiers of a class indicates the same functionality of access specifiers
I've read this very well written blog post by Eric Lippert, but it doesn't explain the specific case of accessibility modifiers.
Conventional stackoverflow wisdom says to always specify "private" explicitly, which would imply that members should have required the modifier.
Well It's not like there's no default modifiers set if not defined. In C# a default modifier is set even if you don't specify so at times you might want to know your default modifiers for your program to execute your way (intended result).
An enum, struct, or class will default to internal under typical conditions (in a namespace or just sitting there alone in a file), but will default to private when declared inside a struct or class.
All methods, fields, and properties has default access modifier as "Private".
Possibly the designers of C# wanted and liked "religious" fights on whether or not to include refundant access modifiers?
(In cases where only one access level is possible, access modifiers are usually disallowed: For example, a member of an interface or an enum is always public but it's not allowed to write that. A partial method is always private but you can't write that. Since a static constructor can't be called explicitly, there's no meaningful access level. An explicit interface implementation is not really visible for direct call, but is freely accessible through the interface type (if the interface type is visible from the outside). Namespaces can have no access modifier.)
The opposite rule from what you suggest, would of course be a rule saying that it is not allowed to specify a modifier that doesn't change anything. That would mean that a direct member of a namespace (including the implicit "global namespace") could not be explicitly declared internal, and that a member of a class or struct (including nested types) could not have the keyword private. Some people use this convention.
Note that getters and setters of properties and indexers cannot specify a redundant access level. The only thing allowed here is for just one of the two accessors (there must be two in that case) to specify a more strict access.
As is usually the case with this type of question, a definitive answer could only come from those who created the language (assuming it is not addressed in the documentation, of course).
But it's probably safe to assume that it is because, in the words of David Naugler, in addition to being a C-based language, "C# has been strongly influenced by Java [and] C++ and is best viewed as a descendant of both(...)."
As a side note, Anders Hejlsberg, the original author of Turbo Pascal and the chief architect of Delphi, is also the lead architect behind the creation of C#.
I realise this is sort of dodging the question, so you may now go ask why does C++ originally allow for optional visibility modifiers =p
I've read around on the internet and I've heard people say
Access specifiers ::
The access specifier determines how
accessible the field is to code in
other classes. Access ranges from
totally accessible to totally
inaccessible. You can optionally
declare a field with an access
specifier keyword: public, private,
or protected.
Access Modifiers ::
You can optionally declare a field
with a modifier keyword: final or
volatile and/or static and/or
transient, abstract, etc.
Is there any difference at all? Because most definitions for access modifiers and access specifiers state the same thing.. which seems so ambiguous.
In this context, you can think of access specifiers as protection specifiers -- they specify where a variable can be accessed from. By contrast, access modifiers are completely different; they specify how variables should (or should not) be accessed; e.g. read-only, volatile, etc.
i.e., a variable can be public but read-only, or it can be private and writable -- the access specifiers have nothing to do with the modifiers.
However, I'm a little surprised that the terminology is for C#, since Microsoft actually calls public and private "access modifiers", and it calls volatile and readonly just plain "modifiers".
As far as I can see, there is no difference at all between the terms. The MS C++ documentation for example uses both terms for the same thing.
Refer from MSDN C# 4.0 document, I think you misunderstand something. C# does not has some word like "access specifier" but it call modifiers or access modifiers for modifiers that use to control access level.
Hope this help.
Update
I think, this question like you ask me that what difference between package and namespace is. It depends on what language or professor that you use or believe. Nothing is wrong on same kind like this question.
From experience (and the meaning of words), access modifier should mean about controlling access like public or private. In the other hand, Access Specifiers should be the super class of access modifier that mean it include other keyword like static, final, readonly or something like that in it.
PS. Both C#, VB.NET and Java, they use access modifier for keyword like public or private. In the other hand, C++ use access specifier for the same keyword.
Modifiers (C# 4.0)
Access Levels in Visual Basic (VB.NET 2010)
Controlling Access to Members of a Class (Java)
Access Specifiers (C++ 2010)
I believe an access specifier determines the visibility for a certain field / method.
An access modifier tells you more about the behavior and use of that field. You can say whether or not the field requires an instantiated object or if it can be overriden.
Access specifiers of a class indicates what other class variables can access in the present class.
Access modifiers of a class indicates the same functionality of access specifiers
I've been playing around with c++ lately and wondered why there were so many global functions. Then I started thinking about programming in c# and how member functions are stored, so I guess my question is if I have a:
public class Foo {
public void Bar() { ... }
}
and then I do something silly like adding 1,000,000 Foo's to a list; does this mean I have 1,000,000 Foo objects sitting in memory each with there own Bar() function? Or does something much more clever happen?
Thanks.
Nope, there is only one instance. All instances of a class point to an object that contains all the instance methods that take an implicit first parameter affectionately called this. When you invoke an instance method on an instance the this pointer for that instance is passed as the first parameter to that method. That is how the method knows all the instance fields and properties for that instance.
For details see CLR via C#.
This is, of course, complicated by virtual methods. CLR via C# will spell out the distinction for you and is highly recommended if you are interested in this subject. Either way, there is still only one instance of each instance method. The issue is just how these methods are resolved.
An instance method is simply a static method with a hidden this parameter.
(virtual methods are a little more complicated)
In C++ a member function doesn't normally require any per-object storage (an exception - virtual functions - is discussed in the next paragraph). Normally, at each point where the function is used the compiler generates CPU-specific machine code to directly call that function, and for inline functions the call may be avoided and the function's affect may be optimally integrated into the caller's code (which can be ~10x faster for small functions such as "getters and setters" that simply read or write one member variable).
For those classes that have one or more virtual functions, each object will have one extra pointer to a per-class table of function pointers and other information. Thus, each object grows by the size of a pointer - typically 4 or 8 bytes.
Addressing your original observation: C++ has more non-member functions (usually in the std namespace), but a namespace serves this purpose better than a class anyway. Indeed, namespaces are effectively logical interfaces for "static" functions and data that can span many "physical" header files. Why should the logical API of a program be compromised by considerations related to physical files and their implications to build times, file-modification-timestamp triggered make tools etc? In trivial cases where the namespace is in one header, C++ could use a class or struct to scope the same declarations, but that's less convenient as it prevents the use of namespace aliases, using namespaces, and Koenig lookup for implicitly searching namespaces matching a function arguments' namespaces - forcing very explicit prefixing at every point of use. It also gives the false impression that the user is intended to instantiate an object from the content.
ReSharper likes to point out multiple functions per ASP.NET page that could be made static. Does it help me if I do make them static? Should I make them static and move them to a utility class?
Performance, namespace pollution etc are all secondary in my view. Ask yourself what is logical. Is the method logically operating on an instance of the type, or is it related to the type itself? If it's the latter, make it a static method. Only move it into a utility class if it's related to a type which isn't under your control.
Sometimes there are methods which logically act on an instance but don't happen to use any of the instance's state yet. For instance, if you were building a file system and you'd got the concept of a directory, but you hadn't implemented it yet, you could write a property returning the kind of the file system object, and it would always be just "file" - but it's logically related to the instance, and so should be an instance method. This is also important if you want to make the method virtual - your particular implementation may need no state, but derived classes might. (For instance, asking a collection whether or not it's read-only - you may not have implemented a read-only form of that collection yet, but it's clearly a property of the collection itself, not the type.)
Static methods versus Instance methods
Static and instance members of the C# Language Specification explains the difference. Generally, static methods can provide a very small performance enhancement over instance methods, but only in somewhat extreme situations (see this answer for some more details on that).
Rule CA1822 in FxCop or Code Analysis states:
"After [marking members as static], the compiler will emit non-virtual call sites to these members which will prevent a check at
runtime for each call that ensures the current object pointer is
non-null. This can result in a measurable performance gain for
performance-sensitive code. In some cases, the failure to access the
current object instance represents a correctness issue."
Utility Class
You shouldn't move them to a utility class unless it makes sense in your design. If the static method relates to a particular type, like a ToRadians(double degrees) method relates to a class representing angles, it makes sense for that method to exist as a static member of that type (note, this is a convoluted example for the purposes of demonstration).
Marking a method as static within a class makes it obvious that it doesn't use any instance members, which can be helpful to know when skimming through the code.
You don't necessarily have to move it to another class unless it's meant to be shared by another class that's just as closely associated, concept-wise.
I'm sure this isn't happening in your case, but one "bad smell" I've seen in some code I've had to suffer through maintaining used a heck of a lot of static methods.
Unfortunately, they were static methods that assumed a particular application state. (why sure, we'll only have one user per application! Why not have the User class keep track of that in static variables?) They were glorified ways of accessing global variables. They also had static constructors (!), which are almost always a bad idea. (I know there are a couple of reasonable exceptions).
However, static methods are quite useful when they factor out domain-logic that doesn't actually depend on the state of an instance of the object. They can make your code a lot more readable.
Just be sure you're putting them in the right place. Are the static methods intrusively manipulating the internal state of other objects? Can a good case be made that their behavior belongs to one of those classes instead? If you're not separating concerns properly, you may be in for headaches later.
This is interesting read:
http://thecuttingledge.com/?p=57
ReSharper isn’t actually suggesting you make your method static.
You should ask yourself why that method is in that class as opposed to, say, one of the classes that shows up in its signature...
but here is what ReSharper documentaion says:
http://confluence.jetbrains.net/display/ReSharper/Member+can+be+made+static
Just to add to #Jason True's answer, it is important to realise that just putting 'static' on a method doesn't guarantee that the method will be 'pure'. It will be stateless with regard to the class in which it is declared, but it may well access other 'static' objects which have state (application configuration etc.), this may not always be a bad thing, but one of the reasons that I personally tend to prefer static methods when I can is that if they are pure, you can test and reason about them in isolation, without having to worry about the surrounding state.
For complex logic within a class, I have found private static methods useful in creating isolated logic, in which the instance inputs are clearly defined in the method signature and no instance side-effects can occur. All outputs must be via return value or out/ref parameters. Breaking down complex logic into side-effect-free code blocks can improve the code's readability and the development team's confidence in it.
On the other hand it can lead to a class polluted by a proliferation of utility methods. As usual, logical naming, documentation, and consistent application of team coding conventions can alleviate this.
You should do what is most readable and intuitive in a given scenario.
The performance argument is not a good one except in the most extreme situations as the only thing that is actually happening is that one extra parameter (this) is getting pushed onto the stack for instance methods.
ReSharper does not check the logic. It only checks whether the method uses instance members.
If the method is private and only called by (maybe just one) instance methods this is a sign to let it an instance method.
I hope you have already understood the difference between static and instance methods. Also, there can be a long answer and a short one. Long answers are already provided by others.
My short answer: Yes, you can convert them to static methods as ReSharper suggests. There is no harm in doing so. Rather, by making the method static, you are actually guarding the method so that you do not unnecessarily slip any instance members into that method. In that way, you can achieve an OOP principle "Minimize the accessibility of classes and members".
When ReSharper is suggesting that an instance method can be converted to a static one, it is actually telling you, "Why the .. this method is sitting in this class but it is not actually using any of its states?" So, it gives you food for thought. Then, it is you who can realize the need for moving that method to a static utility class or not. According to the SOLID principles, a class should have only one core responsibility. So, you can do a better cleanup of your classes in that way. Sometimes, you do need some helper methods even in your instance class. If that is the case, you may keep them within a #region helper.
If the functions are shared across many pages, you could also put them in a base page class, and then have all asp.net pages using that functionality inherit from it (and the functions could still be static as well).
Making a method static means you can call the method from outside the class without first creating an instance of that class. This is helpful when working with third-party vendor objects or add-ons. Imagine if you had to first create a Console object "con" before calling con.Writeline();
It helps to control namespace pollution.
Just my tuppence: Adding all of the shared static methods to a utility class allows you to add
using static className;
to your using statements, which makes the code faster to type and easier to read. For example, I have a large number of what would be called "global variables" in some code I inherited. Rather than make global variables in a class that was an instance class, I set them all as static properties of a global class. It does the job, if messily, and I can just reference the properties by name because I have the static namespace already referenced.
I have no idea if this is good practice or not. I have so much to learn about C# 4/5 and so much legacy code to refactor that I am just trying to let the Roselyn tips guide me.
Joey