Related
Consider the following class snippet with two static member variables:
public static class Foo
{
static string A = GetA(B);
static string B = "required for A";
...
Now, my understanding is that A and B will be initialized when they are accessed for the first time. However, when I executed a fully-realized version of the snippet above where A was accessed before B was initialized, it led to null being passed in to GetA() instead of "required for A". Why isn't the behaviour to start initializing A, then, when it's realized that B is required to initialize A, initialize B, then return to finish the initialization of A?
What are the general rules around this? Why does it behave this way? I've seen other questions that touch on this (When do static variables get initialized in C#?) but they don't answer this question exactly. What is the static variable initialization order in C#? talks primarily about how this works across classes, not within a single class (though Jon Skeet's addendum to his answer -- "By popular demand, here was my original answer when I thought the question was about the initialization order of static variables within a class:...." does answer this question, it's buried in a much longer answer).
In short, don't do this.
Standard ECMA-334 C# Language Specification
15.5.6.2 Static field initialization
The static field variable initializers of a class correspond to a
sequence of assignments that are executed in the textual order in
which they appear in the class declaration (§15.5.6.1). Within a
partial class, the meaning of "textual order" is specified by
§15.5.6.1. If a static constructor (§15.12) exists in the class,
execution of the static field initializers occurs immediately prior to
executing that static constructor. Otherwise, the static field
initializers are executed at an implementation-dependent time prior to
the first use of a static field of that class
The fix is to :
Put them in the order and use Static Constructor,
or just Initialise them in a Static Constructor in turn giving you the ability to control the order of initialisation (given the above information).
Personally i suggest to Initialise them in a Static Constructor, it seems to make it more concrete and understandable, and less likely to be bumped in refactoring
Four quick questions on static variables that the MSDN Faq and other basic guides seem to neglect.
Is public static the same as static public?e.g. public static class Globals
{...}vs.static public class Globals
{...}Same? Different?
It seems that -- like functions -- variables in a public static class in C# require public static status to be seen inside other classes via the static class's named global instance. Why is this? This seems non-intuitive from a naive perspective (it would seem public static class would provide a singular public instance of the class, with any public variables within available). Clearly this is not the case, so I wanted some perspective from C# experts as to why you have to make your member variables in your static class objects static to provide access. (Note: The MSDN Faq contains an example of a non-static class with static member vars, but nary a discussion on what if any differences having static members with a public static class has.) (i.e. What if any consequences are there of the doubly static status?)e.g. public static class Globals
{ public static Camera camera1; }//doubly static
Is there ever a case where public non-static functions within a public static class are appropriate? I can see that you wouldn't want to expose some things, but wouldn't you just want to make them private in such a case. (The simpler the example, the better, I'm self-taught in C# and still trying to understand more complex topics like reflection, etc.)
Curiously public enum inside a public static class are visible without a static keyword via the named global instance. Why is the typical static requirement not enforced here? Is there anything I should worry about if I use the visible public enum rather than a public static enum?public static class Globals
{ public enum Dummy { Everything=42}; } //Enum is visible w/out static!
Thanks in advance. And apologies for the multiple questions, I was on the fence about whether to split this into multiple posts, but it's all related to C# static use, so I figured one post was most appropriate.
1: Order doesn't matter. There are standards of how to order things, for more readability, but as the compiler reads it all - it doesn't matter at all.
I personally thing that it would be best writing it as "public static", instead of "static public".
If you download ReSharper to your Visual Studio, it has predefined prioritizing to modifiers such as "static", "public", "readonly", etc... And will suggest you, when you are not following those standards, to correct the order of the modifiers. If you choose to work with a different prioritizing of the modifiers, you can change the ReSharper's settings to suit your preferred order.
Other than that - ReSharper does many other wonders and it highly recommended.
2: Static classes can only contain static members. "static" in the class means that the class can have no instances, and is declared as a being, sort of, as you said. "static" for members means a different thing: Normally, a member would be owned by the instance. Static members, however, are owned by the class - shared among all instances of the class and are used without an actual instance of the class.
public static class Math
{
public static readonly int ZERO = 0;
}
Here, you can see that ZERO is static, which means it belongs to the class Math.
So you could do:
Math.ZERO
Even if the Math class wasn't static, you would still access the ZERO member via the class itself. The ZERO will not be a member of a Math instance, because it belongs to the class, and not to an instance - hence "static member".
3: Number2 sort of answers this one as well. Non-Static class would mean that it can have instances of it and members that belong the instances, but you could also have class-members (static) that would belong to the class itself.
Example:
public class Quiz
{
public static readonly int FAIL_GRADE = 45;
public int Grade;
public string StudentName;
}
So every Quiz has a grade and a student associated with it, but there is also a constant which belongs to the whole class "Quiz" which indicates what grade is considered as Fail Grade.
In the case above, you could also simply do:
public const int FAIL_GRADE = 45;
So you can learn that "const" means "static readonly", logically speaking.
But in other cases, when you can't use "const" - you would have to use "static readonly".
The "const" can only come before basic types, such as "int", "float", "bool", etc...
Here is an example where the "static" member is not readonly:
public static class Student
{
public static int TestsTaken = 0;
public string Name;
public int DoQuiz(Quiz quiz, Answers answers)
{
TestsTaken++;
// Some answers checking logic and grade returning
}
}
In the above example, you can see that the static member of the class Student is used as a counter to how many times instances of Student performed a certain action (DoQuiz). The use of it here is actually not really good programming, since TestsTaken is really something that should be in Quiz, or in School class. But the example for "static" usage stands.
4: Enums in static classes don't require the "static" keyword, and in fact you can't declare a static Enum anywhere. Enum is not considered a member of a class, but a sub-type of it (could be sub-class, interface, enum, etc).
The fact that an Enum is declared within a class, simply means that if one wishes to use the Enum, he must reference the class as well. It would usually be places within a class for logic purposes, abstraction or encapsulation (would declare it "private" in this case - so it can be used within the class, but not outside of it).
Example:
public static class Math
{
private enum SpecialSigns
{
Sigma,
Alpha,
Pi,
etc
}
}
In the above example, the SpecialSigns enum can be used from within the Math class, but is not visible to the outside.
You could also declare it public, so when one uses Math class, he could also use the SpecialSigns enum. In that case, you could also have SpecialSigns values as return types of methods, or types of public members. You can't do that when the SpecialSigns is private because the outside code does not have access to it - does not know of it's existence - and therefore cannot understand it as a return value, member type, etc.
Still, the SpecialSigns enum is not a member of the class, but only defined within the scope of it's recognition.
According to Method Specification:
A method-declaration may include a set of attributes (Section 17) and a valid combination of the four access modifiers (Section 10.2.3), the new (Section 10.2.2), static (Section 10.5.2), virtual (Section 10.5.3), override (Section 10.5.4), sealed (Section 10.5.5), abstract (Section 10.5.6), and extern (Section 10.5.7) modifiers.
Sequence doesn't matter
Yes, the order doesn't really matter.
Yes, a static class can only contain static members (with exception of #4), but they don't have to be public.
Yes, you can have public static methods, but private static methods that your public static methods use
Nested type declarations are not required to be static.
Another thing to remember is the "internal" visibility in c#. In my code bases I have found many uses for internal static classes (most of the time for extension methods).
There is a lot of code in one of our projects that looks like this:
internal static class Extensions
{
public static string AddFoo(this string s)
{
if (s == null)
{
return "Foo";
}
return $({s}Foo);
}
}
Is there any explicit reason to do this other than "it is easier to make the type public later?"
I suspect it only matters in very strange edge cases (reflection in Silverlight) or not at all.
UPDATE: This question was the subject of my blog in September 2014. Thanks for the great question!
There is considerable debate on this question even within the compiler team itself.
First off, it's wise to understand the rules. A public member of a class or struct is a member that is accessible to anything that can access the containing type. So a public member of an internal class is effectively internal.
So now, given an internal class, should its members that you wish to access in the assembly be marked as public or internal?
My opinion is: mark such members as public.
I use "public" to mean "this member is not an implementation detail". A protected member is an implementation detail; there is something about it that is going to be needed to make a derived class work. An internal member is an implementation detail; something else internal to this assembly needs the member in order to work correctly. A public member says "this member represents the key, documented functionality provided by this object."
Basically, my attitude is: suppose I decided to make this internal class into a public class. In order to do that, I want to change exactly one thing: the accessibility of the class. If turning an internal class into a public class means that I have to also turn an internal member into a public member, then that member was part of the public surface area of the class, and it should have been public in the first place.
Other people disagree. There is a contingent that says that they want to be able to glance at the declaration of a member and immediately know whether it is going to be called only from internal code.
Unfortunately, that doesn't always work out nicely; for example, an internal class that implements an internal interface still has to have the implementing members marked as public, because they are part of the public surface of the class.
If the class is internal, it doesn't matter from an accessibility standpoint whether you mark a method internal or public. However it is still good to use the type you would use if the class were public.
While some have said that this eases transitions from internal to public. It also serves as part of the description of the method. Internal methods typically are considered unsafe for unfettered access, while public methods are considered to be (mostly) free game.
By using internal or public as you would in a public class, you ensure that you are communicating what style of access is expected, while also easing the work required to make the class public in the future.
I suspect that "it is easier to make the type public later?" is it.
The scoping rules mean that the method will only be visible as internal - so it really doesn't matter whether the methods are marked public or internal.
One possibility that comes to mind is that the class was public and was later changed to internal and the developer didn't bother to change all the method accessibility modifiers.
I often mark my methods in internal classes public instead of internal as a) it doesn't really matter and b) I use internal to indicate that the method is internal on purpose (there is some reason why I don't want to expose this method in a public class. Therefore, if I have an internal method I really have to understand the reason why it's internal before changing it to public whereas if I am dealing with a public method in an internal class I really have to think about why the class is internal as opposed to why each method is internal.
In some cases, it may also be that the internal type implements a public interface which would mean that any methods defined on that interface would still need to be declared as public.
It's the same, the public method will be really marked as internal since it's inside a internal class, but it has an advantaje(as you guested), if you want to mark the class as public, you have to change fewer code.
For the same reason as using public methods in any other class - so that they're public to the outside of the containing type.
Type's access modifier has exactly zero to do with its members' access modifiers. The two decisions are made completely independently.
Just because certain combinations of type and members' modifiers produce seemingly (or as others call it "effectively") the same result doesn't mean they're semantically the same.
Local access modifier of a an entity (as declared in code) and its global effective access level (as evaluated through the chain of containment) are completely different things, too. An open office inside of a locked building is still open, even though you can't really enter it from the street.
Don't think of the end effect. Think of what you need locally, first.
Public's Public: classic situation.
Public's Internal: type is public but you want some semi-legal access in the assembly to do some hacky-wacky stuff.
Internal's Public: you hide the whole type but within the assembly it has a classic public surface
Internal's Internal: I can't think of any real world example. Perhaps something soon to become public's internal?
Internal's Public vs Internal's Internal is a false dilemma. The two have completely different meaning and should be used each in their own set of situations, non-overlapping.
internal says the member can only be accessed from within the same assembly. Other classes in that assembly can access the internal public member, but would not be able to access a private or protected member, internal or not.
I actually struggled with this today. Until now I would have said that methods should all be marked with internal if the class was internal and would have considered anything else simply bad coding or laziness, specially in enterprise development; however, I had to sub class a public class and override one of it's methods:
internal class SslStreamEx : System.Net.Security.SslStream
{
public override void Close()
{
try
{
// Send close_notify manually
}
finally
{
base.Close();
}
}
}
The method MUST be public and it got me thinking that there's really no logical point to setting methods as internal unless they really must be, as Eric Lippert said.
Until now I've never really stopped to think about it, I just accepted it, but after reading Eric's post it really got me thinking and after a lot of deliberating it makes a lot of sense.
There does be a difference.
In our project we have made a lot of classes internal, but we do unit test in another assembly and in our assembly info we used InternalsVisibleTo to allow the UnitTest assembly to call the internal classes.
I've noticed if internal class has an internal constructor we are not able to create instance using Activator.CreateInstance in the unit test assembly for some reason. But if we change the constructor to public but class is still internal, it works fine.
But I guess this is a very rare case (Like Eric said in the original post: Reflection).
I think I have an additional opinion on this. At first, I was wondering about how it makes sense to declare something to public in an internal class. Then I have ended up here, reading that it could be good if you later decide to change the class to public. True. So, a pattern formed in my mind: If it does not change the current behavior, then be permissive, and allow things that does not makes sense (and does not hurt) in the current state of code, but later it would, if you change the declaration of the class.
Like this:
public sealed class MyCurrentlySealedClass
{
protected void MyCurretlyPrivateMethod()
{
}
}
According to the "pattern" I have mentioned above, this should be perfectly fine. It follows the same idea. It behaves as a private method, since you can not inherit the class. But if you delete the sealed constraint, it is still valid: the inherited classes can see this method, which is absolutely what I wanted to achieve. But you get a warning: CS0628, or CA1047. Both of them is about do not declare protected members in a sealed class. Moreover, I have found full agreement, about that it is senseless: 'Protected member in sealed class' warning (a singleton class)
So after this warning and the discussion linked, I have decided to make everything internal or less, in an internal class, because it conforms more that kind of thinking, and we don't mix different "patterns".
I want to do the following
public abstract class MyAbstractClass
{
public static abstract int MagicId
{
get;
}
public static void DoSomeMagic()
{
// Need to get the MagicId value defined in the concrete implementation
}
}
public class MyConcreteClass : MyAbstractClass
{
public static override int MagicId
{
get { return 123; }
}
}
However I can't because you can't have static abstract members.
I understand why I can't do this - any recommendations for a design that will achieve much the same result?
(For clarity - I am trying to provide a library with an abstract base class but the concrete versions MUST implement a few properties/methods themselves and yes, there are good reasons for keeping it static.)
You fundamentally can't make DoSomeMagic() work with the current design. A call to MyConcreteClass.DoSomeMagic in source code will be translated into MyAbstractClasss.DoSomeMagic in the IL. The fact that it was originally called using MyConcreteClass is lost.
You might consider having a parallel class hierarchy which has the same methods but virtual - then associate each instance of the original class with an instance of the class containing the previously-static members... and there should probably only be one instance of each of those.
Would the Singleton pattern work perhaps? A link to the MSDN article describing how to implement a singleton in C#:
http://msdn.microsoft.com/en-us/library/ff650316.aspx
In your particular example, the Singelton instance could extend an abstract base class with your MagicId in it.
Just a thought :)
I would question that there are "good reasons" for making the abstract members static.
If your thinking is that these members might reflect some property of the derived class itself rather than a given instance, this does not necessarily mean the members should be static.
Consider the IList.IsFixedSize property. This is really a property of the kind of IList, not any particular instance (i.e., any T[] is going to be fixed size; it will not vary from one T[] to another). But still it should be an instance member. Why? Because since multiple types may implement IList, it will vary from one IList to another.
Consider some code that takes any MyAbstractClass (from your example). If this code is designed properly, in most cases, it should not care which derived class it is actually dealing with. What matters is whatever MyAbstractClass exposes. If you make some abstract members static, basically the only way to access them would be like this:
int magicId;
if (concreteObject is MyConcreteClass) {
magicId = MyConcreteClass.MagicId;
} else if (concreteObject is MyOtherConcreteClass) {
magicId = MyOtherConcreteClass.MagicId;
}
Why such a mess? This is much better, right?
int magicId = concreteObject.MagicId;
But perhaps you have other good reasons that haven't occurred to me.
Your best option is to use an interface with MagicId only using a setter
public interface IMagic
{
int MagicId { get; }
}
By the nature of Static meaning there can only be one (yes like Highlander) you can't override them.
Using an interface assumes your client will implement the contract. If they want to have an instance for each or return the value of a Static variable it is up to them.
The good reason for keeping things static would also mean you do NOT need to have it overridden in the child class.
Not a huge fan of this option but...
You could declare the property static, not abstract, virtual and throw a NotImplementedException which returns an error message that the method has to be overridden in a derived class.
You move the error from compile time to run time though which is kinda ugly.
Languages that implement inheritance of static members do it through metaclasses (that is, classes are also objects, and these objects have a metaclass, and static inheritance exists through it). You can vaguely transpose that to the factory pattern: one class has the magic member and can create objects of the second class.
That, or use reflection. But you can't ensure at compile-time that a derived class implements statically a certain property.
Why not just make it a non-static member?
Sounds like a Monostate, perhaps? http://c2.com/cgi/wiki?MonostatePattern
The provider pattern, used by the ASP.NET membership provider, for example, might be what you're looking for.
You cannot have polymorphic behavior on static members, so you'll have a static class whose members delegate to an interface (or abstract class) field that will encapsulate the polymorphic behaviors.
Suppose that we have a class named class1.
The class1 has several properties and methods and we have decided to specify the access specifier of class1 as internal.
Now, can we set the access specifier of class1 methods as public?
For your specific question, Class 1 which is declared as internal can have a public method.
Why?
Look at Jon Skeets explanation:
You can certainly mark a class as
internal, but that's different from
making its public members internal.
For instance, suppose you have a class
which implements a public interface.
Even though the class may be internal,
an instance may still "get out of the
assembly" by being returned from a
member in another (public) class. That
instance would have to be referenced
by the interface it implements rather
than the class name itself (as the
class isn't known to the outside
assembly) but the public methods can
still be called.
If the public methods aren't
implementing any interfaces, I suspect
it would only make a difference in a
very few reflection cases which you
may not care about.
community wiki - as credit should go to Jon Skeet
Yes, you can set public on members of internal/private/etc types.
As other replies have noted, external code won't be able to see the properties unless it can see the type - but there are lots of nuances:
if the member is on an interface it will be (essentially) part of the public API
the member might be a public override of a virtual/abstract member - in which case it will truly be publicly visible, but via the base-class (again, similar to interfaces)
But there is a lot of other code in the framework that uses reflection and demands public accessibility:
data binding usually works on the public properties
security checks for partial-trust can be fussy about public members
serialization (for example XmlSerializer) may want public members
etc
So there are still lots of reasons to think about public rather than just internal, even if your code is only referenced by the local assembly.
By rule access specifiers on methods and properties can not be more more accessible than that of the class containing it.
But I've tried this:
internal class Test
{
public string Testing{get;set;}
}
and it compiles without any exception! I think it is okay as the class Test will not be accessible outside the namespace assembly we have declared so public property will not make any difference.
This does not works:
private class Test
{
public string Testing{get;set;}
internal string TestingAgain{get;set;}
}