Greetings,
I'm a beginner to OO and programming and I have the following situation:
I have a set of const values and enums that several of the classes I implement share.
These classes are independent i.e. other than sharing these values, they do not interact with each other, so inheriting them won't work.
I was wondering; If I create an empty class with just these consts and enums and then declare an object of these class in each class then i could use these values like:
globals.enum.enummember?
Is this sound programming or is there a better way of doing this?
Thanks for your time.
The best practice is to simply declare the enums alongside with your classes, not nested in a class. Actually, nested types are usually a bad idea, unless they are private. There are exceptions, of course, but for the most part you're better without nesting.
Constants have to be defined in a class, but you don't need to instantiate an object of the class to use them. Also they can be public, so you don't need to inherit anything. If you think about it hard enough, you should be able to figure out a good name for the class that contains these constants.
Practice shows that constants and enums rarely are simply global. Most of the time they are closely coupled with one or few classes. You should then define these constants as a part of the appropriate class and put enums in the same namespace as the class using them.
You can use static class with static members to achieve desired behavior:
namespace A {
public static class Enum1 {
public static readonly int EnumMember1 = 1;
public static readonly int EnumMember2 = 2;
public static readonly int EnumMember3 = 3;
}
}
You should use this in the following way:
int x = A.Enum1.EnumMember2;
Related
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).
Would it be considered a bad practice to nest a private static class inside of a non-static class?
public class Outer
{
private static class Inner
{
}
}
The idea here is that all instances of 'Outer' would share access to the static state. Another way to do it might be to just let the Inner class be non-static and use a static instance of it:
public class Outer
{
private static innerInstance = new Inner();
private class Inner
{
}
}
Similar effect. What are the pros / cons or other considerations with this approach?
I must admit that I almost never use nested classes, whether static or not, but I am interested in this particular concept..
Both approaches are entirely valid.
I wish developers would use private nested classes more often. In conjunction with c#'s partial keyword, it makes writing very complex classes much more maintainable. Imagine needing to build a class that has the complexity of a small application - much easier when you actually can build an entire private application, with classes that are totally internal to your complex outer class!
One very common case I've seen is enumerables - these can be quite complex, especially when you start building custom iterators that can be chained, like LINQ. Hiding the complexity inside the individual classes is the very definition of encapsulation.
If the class is used in a multi-threaded application, you may need to control access to the static state via locking. That's a problem with static state whether privately nested or not.
Nothing wrong with it in principle, though if you're wanting a nested static class to help organize static state or methods, it could be a warning sign that the class is growing too large. Nested private classes have a lot of uses (internal data structures, private implementations of passed out private interfaces, etc.), but a static private class is really just a way to group things together.
Imagine needing to build a class that has the complexity of a small
application ... with classes that are totally internal to your complex
outer class
No, don't imagine it.
Just don't build a class that has the complexity of an application, even if a small application.
By doing so, you will actually increase the complexity.
Use separate classes, each having, ideally, a single responsibility.
That is the way to reduce complexity.
There's nothing wrong at all with this, and why should there be?
The scope is limited, so that only instances of the outer class have access to it, and it's a great place to put constants and other common functionality that is private to the functionality of the outer class, without having to instantiate it all the time.
I don't see this as anything but good practice.
It's depend on what's Inner class do. If it's just a utility class static inner class is way to go.
public class Calculator
{
private static class HexToDecUtils
{
// converter code here
}
}
In other way, if Inner class is composite with other object, it should not be static class.
public class Car
{
private class Engine
{
// your code here
}
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to Use Static Classes in C#
I set my classes as static a lot, but I am not sure when use static or not, or what's the difference it makes to use it or not.
can anybody explain please?
Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.
If a class is declared as static then the variables and methods need to be declared as static.
A class can be declared static, indicating that it contains only static members. It is not possible to create instances of a static class using the new keyword. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace containing the class is loaded.
Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.
->The main features of a static class are:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors or simply constructors as we know that they are associated with objects and operates on data when an object is created.
Example
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
} //class end
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{
//Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//<ClassName>.<MethodName>
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
} //Main end
}
Static classes can be useful in certain situations, but there is a potential to abuse and/or overuse them, like most language features.
As Dylan Smith already mentioned, the most obvious case for using a static class is if you have a class with only static methods. There is no point in allowing developers to instantiate such a class.
The caveat is that an overabundance of static methods may itself indicate a flaw in your design strategy. I find that when you are creating a static function, its a good to ask yourself -- would it be better suited as either a) an instance method, or b) an extension method to an interface. The idea here is that object behaviors are usually associated with object state, meaning the behavior should belong to the object. By using a static function you are implying that the behavior shouldn't belong to any particular object.
Polymorphic and interface driven design are hindered by overusing static functions -- they cannot be overriden in derived classes nor can they be attached to an interface. Its usually better to have your 'helper' functions tied to an interface via an extension method such that all instances of the interface have access to that shared 'helper' functionality.
One situation where static functions are definitely useful, in my opinion, is in creating a .Create() or .New() method to implement logic for object creation, for instance when you want to proxy the object being created,
public class Foo
{
public static Foo New(string fooString)
{
ProxyGenerator generator = new ProxyGenerator();
return (Foo)generator.CreateClassProxy
(typeof(Foo), new object[] { fooString }, new Interceptor());
}
This can be used with a proxying framework (like Castle Dynamic Proxy) where you want to intercept / inject functionality into an object, based on say, certain attributes assigned to its methods. The overall idea is that you need a special constructor because technically you are creating a copy of the original instance with special added functionality.
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.
As stated in the framework design guidelines and the WWW in general, the current guideline is to name your constants like this
LastTemplateIndex
as opposed to
LAST_TEMPLATE_INDEX
With the PascalCasing approach, how do you differentiate between a Property and a Constant.
ErrorCodes.ServerDown is fine. But what about private constants within your class ? I use quite a lot of them for naming magic numbers.. or for expected values in my unit tests and so on.
The ALL_CAPS style helps me know that it is a constant .
_testApp.SelectTemplate(LAST_TEMPLATE_INDEX);
Disclosure: I have been using the SCREAMING_CAPS style for a while for constants + I find it more readable than squishedTogetherPascalCasedName. It actually STANDS_OUT in a block of text
We create a seperate static class to put our constants in and label it Constants.
That way when we access a constant it's always Constant.YourConstantHere
so
class NewClass
{
static class Constants
{
public const int T = -1;
}
}