This question already has answers here:
Why is Main method private?
(4 answers)
Closed 8 years ago.
How does this actually work? I thought Main was supposed to be "called". But how is that possible if it's marked private?
public class Program
{
private static void Main()
{
}
}
From Jon Skeet on bytes.com:
Basically, the execution of the main method is started by special code
within the CLR (or possibly code driving the CLR to start with) which
doesn't need to obey the same rules.
Source
Also, there's another question that covers this topic here already.
Following to MSDN the Main method should not be public:
Main is declared inside a class or struct. Main must be static and
it should not be public. (In the earlier example, it receives the default access of private.) The enclosing class or struct is not
required to be static.
It is a language implementation detail, the CLR simply reads the EntryPointToken value from the assembly header and performs no accessibility checks on the method with that token. The underlying call is _AppDomain.ExecuteAssembly(). So we'll need to turn to the C# Language Specification, section 3.1 mentions the accessibility rule explicitly:
In C#, every method must be defined as a member of a class or struct. Ordinarily, the declared accessibility (§3.5.1) of a method is determined by the access modifiers (§10.3.5) specified in its declaration, and similarly the declared accessibility of a type is determined by the access modifiers specified in its declaration. In order for a given method of a given type to be callable, both the type and the member must be accessible. However, the application entry point is a special case. Specifically, the execution environment can access the application's entry point regardless of its declared accessibility and regardless of the declared accessibility of its enclosing type declarations.
The bolded section documents what the CLR does with the EntryPointToken. The C# compiler could verify accessibility if it wanted to, but doesn't.
the Main method is executed by CLR when ever you execute your code CLR compiler searches for that Main method. Even if you give main in small letters it wont get called.
Acces modifiers in .Net are (really strong) suggestions. You can call any method or access any property/field using reflection. Consider code like this which behaves somewhat like what is actually going on when main gets called.
public class EntryPointAttribute : System.Attribute
{
public string EntryPoint { get; private set; }
public EntryPointAttribute(string entryPoint) { this.EntryPoint = entryPoint; }
}
public static class EntryPointProcessor
{
public static void Process(object theObject)
{
Type t = theObject.GetType();
var ep = t.GetCustomAttributes(typeof(EntryPointAttribute), true).FirstOrDefault();
string entryPointName = ((EntryPointAttribute)ep).EntryPoint;
MethodInfo mi = t.GetMethod(entryPointName, BindingFlags.Static | BindingFlags.NonPublic);
mi.Invoke(null, new object[0] { });
}
}
[EntryPoint("anentrypoint")]
public class entryPointClass
{
private static void anentrypoint()
{
Console.WriteLine("in anentrypoint");
}
}
class Program
{
static void Main(string[] args)
{
EntryPointProcessor.Process(new entryPointClass());
}
}
Related
I'm having a hard time making this work.
The 3 classes FooType, WebApp & IWebApp must not be accessbile \ visible outside of this DLL. So hence the sealed & internal classes.
Issues I'm having are ...
1) In WebApp class, FeeType1 is not accessible in RouteOneBuilder method's parameter.
2) In WebApp class, FeeType1 is not accessible \ visible in switch's case-statement. (need to be visible).
3) In WebApp class, CreditApplication of FeeType1 property is not visible in the switch's case-statement (need to be visible).
Is there a better way to this complicated script? Am I already screwed for exposing classes outside of this DLL? Can all of step 1 to 4 be resolved differently (or be fixed somehow)?
I don't see how can I make this any simplier.
internal static class FooType
{
public class FeeType
{
public FeeType() { }
public string CreditApplication = "Credit Application";
public string CreditVehicle = "Credit Vehicle";
}
public FeeType FeeType1
{
get { return new FeeType(); }
private set { }
}
}
sealed class WebApp : IWebApp
{
public string RouteOneBuilder(FooType.FeeType1 typing)
{
var xml = "";
switch(typing)
{
case FooType.FeeType1.CreditApplication:
xml = "asdf";
break;
default:
throw new Exception("Unknown value");
}
return xml;
}
}
internal interface IWebApp
{
string RouteOneBuilder(FooType.FeeType typing);
}
Your definition of a sealed class is incorrect. It is not an access modifier like public, private, protected and internal. Marking a class sealed only says that it cannot be inherited from; it does not say anything about access per se.
From the MSDN documentation:
When applied to a class, the sealed modifier prevents other classes
from inheriting from it.
That means that you can still provide a public class that is sealed. However, if you try to inherit from a sealed class, you will receive a compiler error like this:
cannot derive from sealed type 'YourNamespace.YourSealedClass'.
Also, I suggest you read this and this regarding internal/public and nested classes.
Now, looking at the code you provided, the following compiler errors pop up:
FooType.FeeType1': cannot declare instance members in a static class
This error means that if the class is declared static, all of the members must be static too.
FooType.FeeType1' is a 'property' but is used like a 'type'
This arises from the fact that the class is static but none of the members are.
Inconsistent accessibility: parameter type 'FooType.FeeType' is less
accessible than method 'IWebApp.RouteOneBuilder(FooType.FeeType)'
The return type and each of the types referenced in the formal parameter list of a method must be at least as accessible as the method itself.
You can find more information about the last error here.
The design is not correct.
If a type is marked as internal this indicates that it should never be accessed outside of its DLL. If this type must be accessed outside of the DLL in which it is declared, it should not be marked internal.
What constraint is preventing you from using a public modifier or from including the types in the same DLL as the consuming code?
In certain cases it is useful for external DLLs or EXEs to view internal members declared in another DLL. One notable case is for unit testing. The code under test may have an internal access modifier, but your test DLL still needs to access the code in order to test it. You can add the following to AssemblyInfo.cs of the project containing the internal members to allow external access.
[assembly:InternalsVisibleTo("Friend1a")]
See InternalsVisibleToAttribute Class for more details.
Side note: The sealed access modifier doesn't prevent access from outside of the declaring DLL. It prevents other types from extending the type.
I'm trying add the ability to lookup elements in a List<KeyValuePair<string,int>> by overriding the indexer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class MyList : List<KeyValuePair<string, int>>
{
public int this[string key]
{
get
{
return base.Single(item => item.Key == key).Value;
}
}
}
}
For some reason, the compiler is throwing this error:
'System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string,int>>' does not contain a definition for 'Single'.
While it is true that List<T> doesn't have that method, it should be visible because it is an extension method from the System.Linq namespace (which is included). Obviously using this.Single resolves the issue, but why is access via base an error?
Section 7.6.8 of the C# spec says
When base.I occurs in a class or struct, I must denote a member of the base class of that class or struct.
Which might seem to preclude access to extension method via base. However it also says
At binding-time, base-access expressions of the form base.I and base[E] are evaluated exactly as if they were written ((B)this).I and ((B)this)[E], where B is the base class of the class or struct in which the construct occurs. Thus, base.I and base[E] correspond to this.I and this[E], except this is viewed as an instance of the base class.
If base.I is just like ((B)this).I then it seems like extension methods should be allowed here.
Can anyone explain the apparent contradiction in these two statements?
Consider this situation:
public class Base
{
public void BaseMethod()
{
}
}
public class Sub : Base
{
public void SubMethod()
{
}
}
public static class Extensions
{
public static void ExtensionMethod(this Base #base) { }
}
Here are some interesting assertions about this code:
I cannot call the extension method using ExtensionMethod() from neither Base nor Sub.
I cannot call base.ExtensionMethod() from Sub.
I can call the extension method using Extensions.ExtensionMethod(this) from both Sub and Base.
I can call the extension method using this.ExtensionMethod() from both Sub and Base.
Why is this?
I don't have a conclusive answer, partly because there might not be one: as you can read in this thread, you have to add this. if you want to call it in the extension method style.
When you're trying to use an extension method from the type it is in (or - consequently - from a type that is derived from the type used in the extension method), the compiler doesn't realize this and will try to call it as a static method without any arguments.
As the answer states: they [the language designers] felt it was not an important use case scenario to support implicit extension methods (to give the beast a name) from within the type because it would encourage extension methods that really should be instance methods and it was considered plain unnecessary.
Now, it is hard to find out what is happening exactly under the covers but from some playing around we can deduce that base.X() does not help us. I can only assume that base.X performs its virtual call as X() and not this.X() from the context of the baseclass.
What do I do when I want to call the extension method of a baseclass from a subclass?
Frankly, I haven't found any truly elegant solution. Consider this scenario:
public class Base
{
protected void BaseMethod()
{
this.ExtensionMethod();
}
}
public class Sub : Base
{
public void SubMethod()
{
// What comes here?
}
}
public static class Extensions
{
public static void ExtensionMethod(this Base #base)
{
Console.WriteLine ("base");
}
public static void ExtensionMethod(this Sub sub)
{
Console.WriteLine ("sub");
}
}
There are 3 ways (leaving aside reflection) to call the ExtensionMethod(Base) overload:
Calling BaseMethod() which forms a proxy between the subclass and the extensionmethod.
You can use BaseMethod(), base.BaseMethod() and this.BaseMethod() for this since now you're just dealing with a normal instance method which in its turn will invoke the extension method. This is a fairly okay solution since you're not polluting the public API but you also have to provide a separate method to do something that should have been accessible in the context in the first place.
Using the extension method as a static method
You can also use the primitive way of writing an extension method by skipping the syntactic sugar and going straight to what it will be compiled as. Now you can pass in a parameter so the compiler doesn't get all confused. Obviously we'll pass a casted version of the current instance so we're targetting the correct overload:
Extensions.ExtensionMethod((Base) this);
Use the - what should be identical translation - of base.ExtensionMethod()
This is inspired by #Mike z's remark about the language spec which says the following:
At binding-time, base-access expressions of the form base.I and base[E] are evaluated exactly as if they were written ((B)this).I and ((B)this)[E], where B is the base class of the class or struct in which the construct occurs. Thus, base.I and base[E] correspond to this.I and this[E], except this is viewed as an instance of the base class.
The spec literally says that base.I will be invoked as ((B) this).I. However in our situation, base.ExtensionMethod(); will throw a compilation error while ((Base) this).ExtensionMethod(); will work perfectly.
It looks like something is wrong either in the documentation or in the compiler but that conclusion should be drawn by someone with deeper knowledge in the matter (paging Dr. Lippert).
Isn't this confusing?
Yes, I would say it is. It kind of feels like a black hole within the C# spec: practically everything works flawlessly but then suddenly you have to jump through some hoops because the compiler doesn't know to inject the current instance in the method call in this scenario.
In fact, intellisense is confused about this situation as well:
We have already determined that that call can never work, yet intellisense believes it might. Also notice how it adds "using PortableClassLibrary" behind the name, indicating that a using directive will be added. This is impossible because the current namespace is in fact PortableClassLibrary. But of course when you actually add that method call:
and everything doesn't work as expected.
Perhaps a conclusion?
The main conclusion is simple: it would have been nice if this niche usage of extension methods would be supported. The main argument for not implementing it was because it would encourage people to write extension methods instead of instance methods.
The obvious problem here is of course that you might not always have access to the base class which makes extension methods a must but by the current implementation it is not possible.
Or, as we've seen, not possibly with the cute syntax.
Try to cast the instance to its base class:
((BaseClass)this).ExtensionMethod()
Applied to your code:
public class Base
{
public void BaseMethod()
{
}
}
public static class BaseExtensions
{
public static void ExtensionMethod(this Base baseObj) { }
}
public class Sub : Base
{
public void SubMethod()
{
( (Base) this).ExtensionMethod();
}
}
This question already has answers here:
Method can be made static, but should it?
(14 answers)
Closed 7 years ago.
Ive inherited some code that are a regular class with some private static methods in them. The code (pseudo code) looks like this
public class Animal
{
private string typeOfAnimal;
public Animal(string typeOfAnimal)
{
this.typeOfAnimal = typeOfAnimal;
}
public void MakeSound()
{
var sound = Animal.GetSound(typeOfAnimal);
// Make use of sound here
}
private static string GetSound(string typeOfAnimal)
{
if(typeOfAnimal == "dog")
return "bark";
else if(typeOfAnimal == "cat")
return "mjau";
}
}
Is there any benefit in doing like this compared to making GetSound a regular instance method?
There is some very minor performance difference in static methods, I think that is actually something the SO guys take advantage of. Also, making the method static gets you a slight readability improvement because of what the keyword implies.
My take on this is usually readability. In this case there are two differences: instances vs static, public vs private. Neither is inherently more beneficial than the other, the benefits only appear depending on intended use. In your case, it has no value being a public method and isn't part of the public API of the type so you make it private, and doesn't want to mutate instance state so you make it static.
By default, ReSharper highlights methods that can be made static.
It is advisable to mark your private methods as static if they are not using any of the instance object for slightly better performance and readability.
Infact the following warning in code analysis is shown if such methods are not marked as private.
CA1822: Mark members as static
Extract from the link -
Members that do not access instance data or call instance methods can
be marked as static (Shared in Visual Basic). After you mark the
methods as static, the compiler will emit nonvirtual call sites to
these members. Emitting nonvirtual call sites will prevent a check at
runtime for each call that makes sure that the current object pointer
is non-null. This can achieve a measurable performance gain for
performance-sensitive code. In some cases, the failure to access the
current object instance represents a correctness issue.
it looks like a bad design.
getSound should not be static but implemented in each inherited class.
use static methods when there is no relation between the instance state to the action itself.
in this case, there is a relation. the instance state (type) is done at runtime
i'd write:
public abstract class Animal {
public abstract string GetSound();
}
public class Dog:Animal{
public string GetSound(){return "bark";}
}
public class Cat:Animal{
public string GetSound(){return "mjau";}
}
I use Resharper tool in visual studio
Consider a very simple class written below.
class Test()
{
//constructors do not have any return type.
Test()
{
System.Console.WriteLine("Hello World!");
}
static Test()
{
System.Console.WriteLine("Hello World in Static constructors");
}
public void A()
{
System.Console.WriteLine("A simple function in a class");
}
}
class Program
{
static void Main(string[] args)
{
var asa = new Test(); //Implicitly Typed local variables.
asa.A();
}
}
Using var (the compiler has to infer the type of the variable from the expression on
the right side of the initialization statement).
I have some clarification questions and they are below.
Extra burden to compiler?
How many constructors a class can have?
Why is static constructor called first ? (I checked out by putting a breakpoint?)
Why not Test asa = new Test(); is not preferred by Resharper?
Is it really a good idea to use Resharper first as a beginner? (Myself being a newbie to C and .net programming!)
Thanks in Advance.
Any extra burden to the compiler is basically irrelevant - it should not be part of your decision about whether or not to use var. As noted in comments, it may well require slightly more work for the compiler when you use explicitly declared variable... but again, it's not going to be significant.
A class can have any number of constructors... although it will become unwieldy pretty quickly.
The static constructor will be called once, before the first use of the class (whether that's via a static method or a constructor call). Read the C# spec for more details - section 10.12 of the C# 5 spec includes:
The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
An instance of the class type is created.
Any of the static members of the class type are referenced.
You can configure ReSharper to suggest alternatives, or treat them as warnings, etc. Make it work however you think it should, on this front.
Negligible if any. The return type would otherwise be compile checked. You shouldn't base decisions on it, anyhow.
As many as you want as long as they are distinguishable.
Static constructors are part of the type definition. They are invoked when the type is first referenced.
What message are you receiving? R# is configurable.
Edit:
(You can't beat the Skeet).
yes, there is some extra work required, but it is possible to use var keyword only in those situations in which it is pretty easy for the compiler to infer the type.
There is no constraint on number of constructors, but there are some rules constructors have to follow (ie: it needs to be clear for the compiler which constructor to call)
I can't telly you why - let's say this is just one of the rules. The interesting thing is beforefieldinit (http://stackoverflow.com/questions/610818/what-does-beforefieldinit-flag-do, http://csharpindepth.com/Articles/General/Beforefieldinit.aspx)
I personally think that in this case it is just a matter of taste. Some people tend to use var as much as they can, while others do the opposite. I try to use when:
I am working with collections (or it takes a lot of text to tell the compiler about the type: instead of:
Dictionary<<OneOfMyClasses, OtherClasss> dictionary = new Dictionary<OneOfMyClasses, OtherClass>();
I tend to use var:
var dictionary = new Dictionary<OneOfMyClasses, OtherClass>();
Please mind that it doesn't affect readability of the code (i.e. it is still easy to understand what is actually happening).
Thanks Everyone. After some time spent on research, I would like to add some points that might help someone.
Disclaimer:(The following points were derived(or even pasted) from codeproject and other such websites.
1) Every single class can have only one static constructor.
Reason: Static constructor must be parameter-less or simply, constructor overloading is not permitted. And since CLR is going to call this constructor, we do not have any control over passing values to this function. As we directly can’t call static constructors, there is no point in having multiple static constructors.
class Test
{
static Test() {...}
static Test(int a) {...} //would throw error as "Static constructor must be parameter less"
}
2) Static constructor should be declared without any access specifier.
Reason: Again CLR is going to call the static constructor not any object of the class. Hence, we donot need any access-specifier.
3) Static constructor must operate only on static variables of that class
Reason: Non-static members are specific to the object instance. There is no point in modifying a variable whose value depend/bind to their specific object instance.
4) Why should I use a static constructor ? Give me one good example
Reason: You can use a static constructor, say when you want to log the operations that you are going to perform using that class. MSDN says "A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file".
5) When exactly a static constructor is called ?
Answer: The user has no control on when the static constructor is executed in the program.
.As others and MSDN points out "A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced."
6)When using base class and derived class in C#, when a new instance of a derived class is created, does base class constructor is called first or derived class constructor is called first?
Answer: The base class constructor is called first and then the derived class constructor.
Code example
class DerivedClass : ParentClass
{
public DerivedClass()
{
Console.WriteLine("Derived class constructor!");
}
}
class ParentClass
{
public ParentClass()
{
System.Console.WriteLine("Parent class constructor!");
}
}
class Program
{
static void Main(string[] args)
{
var a = new DerivedClass(); //Implicitly Typed local variables.
}
}
7) Why in your above examples, both constructors have public access specifier ? What if I specify private or do-not specify access specifier at all?
Answer: When you do not specify access specifier(this case, the constructor automatically becomes private) or whenever you use a private access specifier, the class cannot be instantiated. Whenever a class contain one or more private constructors it strictly (!) cannot be instantiated. This type of constructors are called special instance constructor and is generally used when all the members of a class are static methods. (Probably the Math class should be a good example.)
**8)Bonus question on inheritance. Does a class inherit from two different classes ?
Strictly No. C# supports only direct inheritance and ofcourse you can use interfaces.For example,
interface Test
{
void abc();
}
class DerivedClass : ParentClass, Test //Test should not be a class. It can be a interface.
{
public DerivedClass()
{
Console.WriteLine("Derived class constructor!");
}
public void abc()
{
//should be publicly defined!
//non public method could not implement from interface Test
}
}
class ParentClass
{
public ParentClass()
{
System.Console.WriteLine("Parent class constructor!");
}
}
So I recently ran into this C# statement at work:
public new string SomeFunction(int i)
{
return base.SomeFunction(i);
}
I searched the web but I think I can find a better answer here.
Now, I'm guessing that all this does is return a new string with the same value as the string returned by the call to base.SomeFunction(i)... is this correct?
Also, does this feature exist in other languages (java specifically)?
EDIT:
In my specific case, base.SomeFunction is protected and NOT virtual... does this make a difference? Thanks
No, it means that it's hiding SomeFunction in the base class rather than overriding it. If there weren't a method in the base class with the same signature, you'd get a compile-time error (because you'd be trying to hide something that wasn't there!)
See this question for more information. (I don't think this is a duplicate question, as it's about what "new" is for at all rather than just talking about the warning when it's absent.)
Duplicate example from my answer on that question though, just to save the clickthrough...
Here's an example of the difference between hiding a method and overriding it:
using System;
class Base
{
public virtual void OverrideMe()
{
Console.WriteLine("Base.OverrideMe");
}
public virtual void HideMe()
{
Console.WriteLine("Base.HideMe");
}
}
class Derived : Base
{
public override void OverrideMe()
{
Console.WriteLine("Derived.OverrideMe");
}
public new void HideMe()
{
Console.WriteLine("Derived.HideMe");
}
}
class Test
{
static void Main()
{
Base x = new Derived();
x.OverrideMe();
x.HideMe();
}
}
The output is:
Derived.OverrideMe
Base.HideMe
'new' is the member-hiding keyword. From the docs:
When used as a modifier, the new
keyword explicitly hides a member
inherited from a base class. When you
hide an inherited member, the derived
version of the member replaces the
base-class version. Although you can
hide members without the use of the
new modifier, the result is a warning.
If you use new to explicitly hide a
member, it suppresses this warning and
documents the fact that the derived
version is intended as a replacement.
The intent behind your sample code is to make the function public in the child, even though it was protected in the base. The language doesn't let you make a class member more visible in the child, so this instead declares a new function that happens to have the same name. This hides the base function, but then again, the caller wouldn't have had access to that one in the first place, while this function calls the one in the base.
In short, the code is a bit of a hack, but it does make sense. It's probably a hint that the base might need its functionality refactored, though.