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).
I need to know how to prevent a class from being Instantiated in .net?
I know few methods like making the class Abstract and Static.
Is there any more way to achieve this?
Making the class static is the best approach, if you absolutely don't want any instances. This stops anyone from creating instances. The class will be both sealed and abstract, and won't have any constructors.
Additionally, the language will notice that it's a static class and stop you from using it in various places which imply instances, e.g. type arguments and variables. This indicates the intention more clearly than just having a private constructor - which could mean that there are instances, created within that class (e.g. for a singleton implementation).
Oh, and making the class static will stop you from introducing any pointless instance members in the class, too :)
See MSDN for more information about static classes.
Mark the constructor(s) private, protected or if in used from another assembly, internal
Marking the constructor private. Of course, this doesn't prevent the class from instantiating itself through a static method, for example...
More practically, what's the purpose of disallowing class instantiation. If it's to have a singleton, then a private constructor is appropriate. If it's to force subclassing, making the class abstract is better; if it's to have a class with utility methods, making it static is one way (then you can only have static methods).
I need to know how to prevent a class from being Instantiated in .net?
Your question is not clear.
Do you mean instantiated at runtime? Make the class abstract or static.
Do you mean that the constructor is not accessible in code? Make the constructor private. But note that someone could still use reflection to grab a handle on a constructor and instantiate an instance at runtime.
So, which do you mean?
If the question is:
How can you make your class not be instanced without having your class
be static or abstract?
Then the answer to this is to implement the singleton pattern, which in .NET 4+ this is done easily with:
public sealed class myClass
{
private static readonly Lazy<myClass> lazyInstance =
new Lazy<myClass>(() => new myClass());
public static Instance
{
get
{
return lazyInstance.Value;
}
}
private myClass()
{
// constructor logic here
}
}
The singleton pattern allows you to pass your class around as a reference to methods, while still ensuring that you have only a single instance of your class. It also makes testing much easier as you can have a ImyClass instance which myClass implements, this is very helpful when making mock objects.
Without .NET4 you can still implement the singleton pattern, for example:
private static readonly myClass instance = new myClass();
public static Instance
{
get
{
return instance;
}
}
// rest of code remains the same
Which doesn't have deferred loading until it's called, there's lots of other ways as well (I think about 6 different ways), but the above two are the most common ones.
In summary the question is likely asking if you know the singleton pattern and if you recognise it's importance over static classes for unit tests and mock objects.
As others have already pointed out, static fields, even those marked readonly can be set with reflection, in addition the private constructor can be called using reflection. If you need to prevent these, either you need to make the calling code run in a less trusted app-domain space, or you will need to implement your class as static.
Generally though, people don't bother with such levels of reflection to get around your constraints unless they 'really need to' for example, writing obscure / extreme fringe case unit tests.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
When to Use Static Classes in C#
why anyone would write a static class. we can declare a static method in any class and just call that method without creating class instance. so please tell me in what type of situation a person would create a static class and also tell me what are the main differences between static class and normal class.
thanks
A static class cannot be instantiated. It's main uses are to make it clear that the class has no instance methods and to prevent people from accidentally trying to "new" the class.
Generally I would advise you not to write static classes.
There are cases where you want them though
Extension methods have to live on static classes. This is the best reason to have a static class.
If you do have a bunch of static methods that don't make sense as extension methods and don't fit into your object model then there might be room for a collection of static methods. This is particularly the case when you cannot redesign your app.
Sometimes this happens because you are dealing with some 3rd party stuff that you cannot change. Then if you end up with a class with only static methods on it - you should make it static since anyone creating an instance is clearly not understanding what you have done.
Having said all of that for the most part my advices is avoid static methods, classes and data. I am not saying never use them - just try not to.
A static class cannot contain any constructors, only a static constructor that is called first time one of its members is accessed.
That is basically the difference. Performance wise we also get another for free by the compiler since it can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are also sealed and therefore cannot be inherited.
http://msdn.microsoft.com/en-us/library/79b3xss3(v=VS.100).aspx
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type.
Another valid point is that Extension Methods has to be declared in a static class
http://en.wikipedia.org/wiki/Extension_method
The new language feature of extension methods in C# 3.0, however, makes the latter code possible. This approach requires a static class and a static method.
In static class all method all static. we can not declare normal method in static class.
differences between static class and normal class.
We can not create object of static class, when we use method of static class just use classname.MethodName but in normal class we have to first create object of class then we can access method of normal class.
static class ex.
Class1.functionname();
normal class ex.
Class1 cs = new class1();
cs.functionname();
functionname should not be private.
The difference is that you can't instantiate a static class. So you'd make a class static if you don't want it ever being instantiated. This is useful in cases when you're dealing with threading issues, and you want all threads to be guaranteed to use the same instance of your class.
A more philosophical scenario is when you have a class that doesn't need to be instantiated, such as (for example) you're building a database application and you create one class to do all the database access stuff. It's basically just a collection of methods. Then making the class static simply becomes a step to make your design more consistent.
I have several classes that do not really need any state. From the organizational point of view, I would like to put them into hierarchy.
But it seems I can't declare inheritance for static classes.
Something like that:
public static class Base
{
}
public static class Inherited : Base
{
}
will not work.
Why have the designers of the language closed that possibility?
Citation from here:
This is actually by design. There seems to be no good reason to inherit a static class. It has public static members that you can always access via the class name itself. The only reasons I have seen for inheriting static stuff have been bad ones, such as saving a couple of characters of typing.
There may be reason to consider mechanisms to bring static members directly into scope (and we will in fact consider this after the Orcas product cycle), but static class inheritance is not the way to go: It is the wrong mechanism to use, and works only for static members that happen to reside in a static class.
(Mads Torgersen, C# Language PM)
Other opinions from channel9
Inheritance in .NET works only on instance base. Static methods are defined on the type level not on the instance level. That is why overriding doesn't work with static methods/properties/events...
Static methods are only held once in memory. There is no virtual table etc. that is created for them.
If you invoke an instance method in .NET, you always give it the current instance. This is hidden by the .NET runtime, but it happens. Each instance method has as first argument a pointer (reference) to the object that the method is run on. This doesn't happen with static methods (as they are defined on type level). How should the compiler decide to select the method to invoke?
(littleguru)
And as a valuable idea, littleguru has a partial "workaround" for this issue: the Singleton pattern.
The main reason that you cannot inherit a static class is that they are abstract and sealed (this also prevents any instance of them from being created).
So this:
static class Foo { }
compiles to this IL:
.class private abstract auto ansi sealed beforefieldinit Foo
extends [mscorlib]System.Object
{
}
Think about it this way: you access static members via type name, like this:
MyStaticType.MyStaticMember();
Were you to inherit from that class, you would have to access it via the new type name:
MyNewType.MyStaticMember();
Thus, the new item bears no relationships to the original when used in code. There would be no way to take advantage of any inheritance relationship for things like polymorphism.
Perhaps you're thinking you just want to extend some of the items in the original class. In that case, there's nothing preventing you from just using a member of the original in an entirely new type.
Perhaps you want to add methods to an existing static type. You can do that already via extension methods.
Perhaps you want to be able to pass a static Type to a function at runtime and call a method on that type, without knowing exactly what the method does. In that case, you can use an Interface.
So, in the end you don't really gain anything from inheriting static classes.
Hmmm... would it be much different if you just had non-static classes filled with static methods..?
What you want to achieve by using class hierarchy can be achieved merely through namespacing. So languages that support namespapces ( like C#) will have no use of implementing class hierarchy of static classes. Since you can not instantiate any of the classes, all you need is a hierarchical organization of class definitions which you can obtain through the use of namespaces
You can use composition instead... this will allow you to access class objects from the static type. But still cant implements interfaces or abstract classes
Although you can access "inherited" static members through the inherited classes name, static members are not really inherited. This is in part why they can't be virtual or abstract and can't be overridden. In your example, if you declared a Base.Method(), the compiler will map a call to Inherited.Method() back to Base.Method() anyway. You might as well call Base.Method() explicitly. You can write a small test and see the result with Reflector.
So... if you can't inherit static members, and if static classes can contain only static members, what good would inheriting a static class do?
A workaround you can do is not use static classes but hide the constructor so the classes static members are the only thing accessible outside the class. The result is an inheritable "static" class essentially:
public class TestClass<T>
{
protected TestClass()
{ }
public static T Add(T x, T y)
{
return (dynamic)x + (dynamic)y;
}
}
public class TestClass : TestClass<double>
{
// Inherited classes will also need to have protected constructors to prevent people from creating instances of them.
protected TestClass()
{ }
}
TestClass.Add(3.0, 4.0)
TestClass<int>.Add(3, 4)
// Creating a class instance is not allowed because the constructors are inaccessible.
// new TestClass();
// new TestClass<int>();
Unfortunately because of the "by-design" language limitation we can't do:
public static class TestClass<T>
{
public static T Add(T x, T y)
{
return (dynamic)x + (dynamic)y;
}
}
public static class TestClass : TestClass<double>
{
}
You can do something that will look like static inheritance.
Here is the trick:
public abstract class StaticBase<TSuccessor>
where TSuccessor : StaticBase<TSuccessor>, new()
{
protected static readonly TSuccessor Instance = new TSuccessor();
}
Then you can do this:
public class Base : StaticBase<Base>
{
public Base()
{
}
public void MethodA()
{
}
}
public class Inherited : Base
{
private Inherited()
{
}
public new static void MethodA()
{
Instance.MethodA();
}
}
The Inherited class is not static itself, but we don't allow to create it. It actually has inherited static constructor which builds Base, and all properties and methods of Base available as static. Now the only thing left to do make static wrappers for each method and property you need to expose to your static context.
There are downsides like the need for manual creation of static wrapper methods and new keyword. But this approach helps support something that is really similar to static inheritance.
P.S.
We used this for creating compiled queries, and this actually can be replaced with ConcurrentDictionary, but a static read-only field with its thread safety was good enough.
My answer: poor design choice. ;-)
This is an interesting debate focused on syntax impact. The core of the argument, in my view, is that a design decision led to sealed static classes. A focus on transparency of the static class's names appearing at the top level instead of hiding ('confusing') behind child names? One can image a language implementation that could access the base or the child directly, confusing.
A pseudo example, assuming static inheritance was defined in some way.
public static class MyStaticBase
{
SomeType AttributeBase;
}
public static class MyStaticChild : MyStaticBase
{
SomeType AttributeChild;
}
would lead to:
// ...
DoSomethingTo(MyStaticBase.AttributeBase);
// ...
which could (would?) impact the same storage as
// ...
DoSomethingTo(MyStaticChild.AttributeBase);
// ...
Very confusing!
But wait! How would the compiler deal with MyStaticBase and MyStaticChild having the same signature defined in both? If the child overrides than my above example would NOT change the same storage, maybe? This leads to even more confusion.
I believe there is a strong informational space justification for limited static inheritance. More on the limits shortly. This pseudocode shows the value:
public static class MyStaticBase<T>
{
public static T Payload;
public static void Load(StorageSpecs);
public static void Save(StorageSpecs);
public static SomeType AttributeBase
public static SomeType MethodBase(){/*...*/};
}
Then you get:
public static class MyStaticChild : MyStaticBase<MyChildPlayloadType>
{
public static SomeType AttributeChild;
public static SomeType SomeChildMethod(){/*...*/};
// No need to create the PlayLoad, Load(), and Save().
// You, 'should' be prevented from creating them, more on this in a sec...
}
Usage looks like:
// ...
MyStaticChild.Load(FileNamePath);
MyStaticChild.Save(FileNamePath);
doSomeThing(MyStaticChild.Payload.Attribute);
doSomething(MyStaticChild.AttributeBase);
doSomeThing(MyStaticChild.AttributeChild);
// ...
The person creating the static child does not need to think about the serialization process as long as they understand any limitations that might be placed on the platform's or environment's serialization engine.
Statics (singletons and other forms of 'globals') often come up around configuration storage. Static inheritance would allow this sort of responsibility allocation to be cleanly represented in the syntax to match a hierarchy of configurations. Though, as I showed, there is plenty of potential for massive ambiguity if basic static inheritance concepts are implemented.
I believe the right design choice would be to allow static inheritance with specific limitations:
No override of anything. The child cannot replace the base
attributes, fields, or methods,... Overloading should be ok, as
long as there is a difference in signature allowing the compiler to
sort out child vs base.
Only allow generic static bases, you cannot inherit from a
non-generic static base.
You could still change the same store via a generic reference MyStaticBase<ChildPayload>.SomeBaseField. But you would be discouraged since the generic type would have to be specified. While the child reference would be cleaner: MyStaticChild.SomeBaseField.
I am not a compiler writer so I am not sure if I am missing something about the difficulties of implementing these limitations in a compiler. That said, I am a strong believer that there is an informational space need for limited static inheritance and the basic answer is that you can't because of a poor (or over simple) design choice.
Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.
A class can be declared static, which indicates that it contains only static members. It is not possible to use the new keyword to create instances of a static class. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace that contains 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.
Following are the main features of a static class:
They only contain static members.
They cannot be instantiated.
They are sealed.
They cannot contain Instance Constructors (C# Programming Guide).
Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.
The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.
Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can have a static constructor. For more information, see Static Constructors (C# Programming Guide).
When we create a static class that contains only the static members and a private constructor.The only reason is that the static constructor prevent the class from being instantiated for that we can not inherit a static class .The only way to access the member of the static class by using the class name itself.Try to inherit a static class is not a good idea.
I run into the problem when trying to code an IComparer<T> implementation against a third-party library where T is an enum embedded in a class as in the following:
public class TheClass
{
public enum EnumOfInterest
{
}
}
But because the enum is defined within a third-party library class, I can't write the comparer because the following gives a "cannot extends list" error:
public class MyComparer : IComparer<TheClass.EnumOfInterest>
{
}
I'm not even extending a static class -- I'm just implementing a comparer of a enum defined in a class.
Why was C# designed this way?
As I understand it, an interface only describes behaviour, and serves the purpose of describing a contractual obligation for classes implementing the interface that certain behaviour is implemented.
If classes wish to implement that behavour in a shared method, why shouldn't they?
Here is an example of what I have in mind:
// These items will be displayed in a list on the screen.
public interface IListItem {
string ScreenName();
...
}
public class Animal: IListItem {
// All animals will be called "Animal".
public static string ScreenName() {
return "Animal";
}
....
}
public class Person: IListItem {
private string name;
// All persons will be called by their individual names.
public string ScreenName() {
return name;
}
....
}
Assuming you are asking why you can't do this:
public interface IFoo {
void Bar();
}
public class Foo: IFoo {
public static void Bar() {}
}
This doesn't make sense to me, semantically. Methods specified on an interface should be there to specify the contract for interacting with an object. Static methods do not allow you to interact with an object - if you find yourself in the position where your implementation could be made static, you may need to ask yourself if that method really belongs in the interface.
To implement your example, I would give Animal a const property, which would still allow it to be accessed from a static context, and return that value in the implementation.
public class Animal: IListItem {
/* Can be tough to come up with a different, yet meaningful name!
* A different casing convention, like Java has, would help here.
*/
public const string AnimalScreenName = "Animal";
public string ScreenName(){ return AnimalScreenName; }
}
For a more complicated situation, you could always declare another static method and delegate to that. In trying come up with an example, I couldn't think of any reason you would do something non-trivial in both a static and instance context, so I'll spare you a FooBar blob, and take it as an indication that it might not be a good idea.
My (simplified) technical reason is that static methods are not in the vtable, and the call site is chosen at compile time. It's the same reason you can't have override or virtual static members. For more details, you'd need a CS grad or compiler wonk - of which I'm neither.
For the political reason, I'll quote Eric Lippert (who is a compiler wonk, and holds a Bachelor of Mathematics, Computer science and Applied Mathematics from University of Waterloo (source: LinkedIn):
...the core design principle of static methods, the principle that gives them their name...[is]...it can always be determined exactly, at compile time, what method will be called. That is, the method can be resolved solely by static analysis of the code.
Note that Lippert does leave room for a so-called type method:
That is, a method associated with a type (like a static), which does not take a non-nullable “this” argument (unlike an instance or virtual), but one where the method called would depend on the constructed type of T (unlike a static, which must be determinable at compile time).
but is yet to be convinced of its usefulness.
Most answers here seem to miss the whole point. Polymorphism can be used not only between instances, but also between types. This is often needed, when we use generics.
Suppose we have type parameter in generic method and we need to do some operation with it. We dont want to instantinate, because we are unaware of the constructors.
For example:
Repository GetRepository<T>()
{
//need to call T.IsQueryable, but can't!!!
//need to call T.RowCount
//need to call T.DoSomeStaticMath(int param)
}
...
var r = GetRepository<Customer>()
Unfortunately, I can come up only with "ugly" alternatives:
Use reflection
Ugly and beats the idea of interfaces and polymorphism.
Create completely separate factory class
This might greatly increase the complexity of the code. For example, if we are trying to model domain objects, each object would need another repository class.
Instantiate and then call the desired interface method
This can be hard to implement even if we control the source for the classes, used as generic parameters. The reason is that, for example we might need the instances to be only in well-known, "connected to DB" state.
Example:
public class Customer
{
//create new customer
public Customer(Transaction t) { ... }
//open existing customer
public Customer(Transaction t, int id) { ... }
void SomeOtherMethod()
{
//do work...
}
}
in order to use instantination for solving the static interface problem we need to do the following thing:
public class Customer: IDoSomeStaticMath
{
//create new customer
public Customer(Transaction t) { ... }
//open existing customer
public Customer(Transaction t, int id) { ... }
//dummy instance
public Customer() { IsDummy = true; }
int DoSomeStaticMath(int a) { }
void SomeOtherMethod()
{
if(!IsDummy)
{
//do work...
}
}
}
This is obviously ugly and also unnecessary complicates the code for all other methods. Obviously, not an elegant solution either!
I know it's an old question, but it's interesting. The example isn't the best. I think it would be much clearer if you showed a usage case:
string DoSomething<T>() where T:ISomeFunction
{
if (T.someFunction())
...
}
Merely being able to have static methods implement an interface would not achieve what you want; what would be needed would be to have static members as part of an interface. I can certainly imagine many usage cases for that, especially when it comes to being able to create things. Two approaches I could offer which might be helpful:
Create a static generic class whose type parameter will be the type you'd be passing to DoSomething above. Each variation of this class will have one or more static members holding stuff related to that type. This information could supplied either by having each class of interest call a "register information" routine, or by using Reflection to get the information when the class variation's static constructor is run. I believe the latter approach is used by things like Comparer<T>.Default().
For each class T of interest, define a class or struct which implements IGetWhateverClassInfo<T> and satisfies a "new" constraint. The class won't actually contain any fields, but will have a static property which returns a static field with the type information. Pass the type of that class or struct to the generic routine in question, which will be able to create an instance and use it to get information about the other class. If you use a class for this purpose, you should probably define a static generic class as indicated above, to avoid having to construct a new descriptor-object instance each time. If you use a struct, instantiation cost should be nil, but every different struct type would require a different expansion of the DoSomething routine.
None of these approaches is really appealing. On the other hand, I would expect that if the mechanisms existed in CLR to provide this sort of functionality cleanly, .net would allow one to specify parameterized "new" constraints (since knowing if a class has a constructor with a particular signature would seem to be comparable in difficulty to knowing if it has a static method with a particular signature).
Short-sightedness, I'd guess.
When originally designed, interfaces were intended only to be used with instances of class
IMyInterface val = GetObjectImplementingIMyInterface();
val.SomeThingDefinedinInterface();
It was only with the introduction of interfaces as constraints for generics did adding a static method to an interface have a practical use.
(responding to comment:) I believe changing it now would require a change to the CLR, which would lead to incompatibilities with existing assemblies.
To the extent that interfaces represent "contracts", it seems quiet reasonable for static classes to implement interfaces.
The above arguments all seem to miss this point about contracts.
Interfaces specify behavior of an object.
Static methods do not specify a behavior of an object, but behavior that affects an object in some way.
Because the purpose of an interface is to allow polymorphism, being able to pass an instance of any number of defined classes that have all been defined to implement the defined interface... guaranteeing that within your polymorphic call, the code will be able to find the method you are calling. it makes no sense to allow a static method to implement the interface,
How would you call it??
public interface MyInterface { void MyMethod(); }
public class MyClass: MyInterface
{
public static void MyMethod() { //Do Something; }
}
// inside of some other class ...
// How would you call the method on the interface ???
MyClass.MyMethod(); // this calls the method normally
// not through the interface...
// This next fails you can't cast a classname to a different type...
// Only instances can be Cast to a different type...
MyInterface myItf = MyClass as MyInterface;
Actually, it does.
As of Mid-2022, the current version of C# has full support for so-called static abstract members:
interface INumber<T>
{
static abstract T Zero { get; }
}
struct Fraction : INumber<Fraction>
{
public static Fraction Zero { get; } = new Fraction();
public long Numerator;
public ulong Denominator;
....
}
Please note that depending on your version of Visual Studio and your installed .NET SDK, you'll either have to update at least one of them (or maybe both), or that you'll have to enable preview features (see Use preview features & preview language in Visual Studio).
See more:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members
https://blog.ndepend.com/c-11-static-abstract-members/
https://khalidabuhakmeh.com/static-abstract-members-in-csharp-10-interfaces#:~:text=Static%20abstract%20members%20allow%20each,like%20any%20other%20interface%20definition.
Regarding static methods used in non-generic contexts I agree that it doesn't make much sense to allow them in interfaces, since you wouldn't be able to call them if you had a reference to the interface anyway. However there is a fundamental hole in the language design created by using interfaces NOT in a polymorphic context, but in a generic one. In this case the interface is not an interface at all but rather a constraint. Because C# has no concept of a constraint outside of an interface it is missing substantial functionality. Case in point:
T SumElements<T>(T initVal, T[] values)
{
foreach (var v in values)
{
initVal += v;
}
}
Here there is no polymorphism, the generic uses the actual type of the object and calls the += operator, but this fails since it can't say for sure that that operator exists. The simple solution is to specify it in the constraint; the simple solution is impossible because operators are static and static methods can't be in an interface and (here is the problem) constraints are represented as interfaces.
What C# needs is a real constraint type, all interfaces would also be constraints, but not all constraints would be interfaces then you could do this:
constraint CHasPlusEquals
{
static CHasPlusEquals operator + (CHasPlusEquals a, CHasPlusEquals b);
}
T SumElements<T>(T initVal, T[] values) where T : CHasPlusEquals
{
foreach (var v in values)
{
initVal += v;
}
}
There has been lots of talk already about making an IArithmetic for all numeric types to implement, but there is concern about efficiency, since a constraint is not a polymorphic construct, making a CArithmetic constraint would solve that problem.
Because interfaces are in inheritance structure, and static methods don't inherit well.
What you seem to want would allow for a static method to be called via both the Type or any instance of that type. This would at very least result in ambiguity which is not a desirable trait.
There would be endless debates about whether it mattered, which is best practice and whether there are performance issues doing it one way or another. By simply not supporting it C# saves us having to worry about it.
Its also likely that a compilier that conformed to this desire would lose some optimisations that may come with a more strict separation between instance and static methods.
You can think of the static methods and non-static methods of a class as being different interfaces. When called, static methods resolve to the singleton static class object, and non-static methods resolve to the instance of the class you deal with. So, if you use static and non-static methods in an interface, you'd effectively be declaring two interfaces when really we want interfaces to be used to access one cohesive thing.
To give an example where I am missing either static implementation of interface methods or what Mark Brackett introduced as the "so-called type method":
When reading from a database storage, we have a generic DataTable class that handles reading from a table of any structure. All table specific information is put in one class per table that also holds data for one row from the DB and which must implement an IDataRow interface. Included in the IDataRow is a description of the structure of the table to read from the database. The DataTable must ask for the datastructure from the IDataRow before reading from the DB. Currently this looks like:
interface IDataRow {
string GetDataSTructre(); // How to read data from the DB
void Read(IDBDataRow); // How to populate this datarow from DB data
}
public class DataTable<T> : List<T> where T : IDataRow {
public string GetDataStructure()
// Desired: Static or Type method:
// return (T.GetDataStructure());
// Required: Instantiate a new class:
return (new T().GetDataStructure());
}
}
The GetDataStructure is only required once for each table to read, the overhead for instantiating one more instance is minimal. However, it would be nice in this case here.
FYI: You could get a similar behavior to what you want by creating extension methods for the interface. The extension method would be a shared, non overridable static behavior. However, unfortunately, this static method would not be part of the contract.
Interfaces are abstract sets of defined available functionality.
Whether or not a method in that interface behaves as static or not is an implementation detail that should be hidden behind the interface. It would be wrong to define an interface method as static because you would be unnecessarily forcing the method to be implemented in a certain way.
If methods were defined as static, the class implementing the interface wouldn't be as encapsulated as it could be. Encapsulation is a good thing to strive for in object oriented design (I won't go into why, you can read that here: http://en.wikipedia.org/wiki/Object-oriented). For this reason, static methods aren't permitted in interfaces.
Static classes should be able to do this so they can be used generically. I had to instead implement a Singleton to achieve the desired results.
I had a bunch of Static Business Layer classes that implemented CRUD methods like "Create", "Read", "Update", "Delete" for each entity type like "User", "Team", ect.. Then I created a base control that had an abstract property for the Business Layer class that implemented the CRUD methods. This allowed me to automate the "Create", "Read", "Update", "Delete" operations from the base class. I had to use a Singleton because of the Static limitation.
Most people seem to forget that in OOP Classes are objects too, and so they have messages, which for some reason c# calls "static method".
The fact that differences exist between instance objects and class objects only shows flaws or shortcomings in the language.
Optimist about c# though...
OK here is an example of needing a 'type method'. I am creating one of a set of classes based on some source XML. So I have a
static public bool IsHandled(XElement xml)
function which is called in turn on each class.
The function should be static as otherwise we waste time creating inappropriate objects.
As #Ian Boyde points out it could be done in a factory class, but this just adds complexity.
It would be nice to add it to the interface to force class implementors to implement it. This would not cause significant overhead - it is only a compile/link time check and does not affect the vtable.
However, it would also be a fairly minor improvement. As the method is static, I as the caller, must call it explicitly and so get an immediate compile error if it is not implemented. Allowing it to be specified on the interface would mean this error comes marginally earlier in the development cycle, but this is trivial compared to other broken-interface issues.
So it is a minor potential feature which on balance is probably best left out.
The fact that a static class is implemented in C# by Microsoft creating a special instance of a class with the static elements is just an oddity of how static functionality is achieved. It is isn't a theoretical point.
An interface SHOULD be a descriptor of the class interface - or how it is interacted with, and that should include interactions that are static. The general definition of interface (from Meriam-Webster): the place or area at which different things meet and communicate with or affect each other. When you omit static components of a class or static classes entirely, we are ignoring large sections of how these bad boys interact.
Here is a very clear example of where being able to use interfaces with static classes would be quite useful:
public interface ICrudModel<T, Tk>
{
Boolean Create(T obj);
T Retrieve(Tk key);
Boolean Update(T obj);
Boolean Delete(T obj);
}
Currently, I write the static classes that contain these methods without any kind of checking to make sure that I haven't forgotten anything. Is like the bad old days of programming before OOP.
C# and the CLR should support static methods in interfaces as Java does. The static modifier is part of a contract definition and does have meaning, specifically that the behavior and return value do not vary base on instance although it may still vary from call to call.
That said, I recommend that when you want to use a static method in an interface and cannot, use an annotation instead. You will get the functionality you are looking for.
Static Methods within an Interface are allowed as of c# 9 (see https://www.dotnetcurry.com/csharp/simpler-code-with-csharp-9).
I think the short answer is "because it is of zero usefulness".
To call an interface method, you need an instance of the type. From instance methods you can call any static methods you want to.
I think the question is getting at the fact that C# needs another keyword, for precisely this sort of situation. You want a method whose return value depends only on the type on which it is called. You can't call it "static" if said type is unknown. But once the type becomes known, it will become static. "Unresolved static" is the idea -- it's not static yet, but once we know the receiving type, it will be. This is a perfectly good concept, which is why programmers keep asking for it. But it didn't quite fit into the way the designers thought about the language.
Since it's not available, I have taken to using non-static methods in the way shown below. Not exactly ideal, but I can't see any approach that makes more sense, at least not for me.
public interface IZeroWrapper<TNumber> {
TNumber Zero {get;}
}
public class DoubleWrapper: IZeroWrapper<double> {
public double Zero { get { return 0; } }
}
As per Object oriented concept Interface implemented by classes and
have contract to access these implemented function(or methods) using
object.
So if you want to access Interface Contract methods you have to create object. It is always must that is not allowed in case of Static methods. Static classes ,method and variables never require objects and load in memory without creating object of that area(or class) or you can say do not require Object Creation.
Conceptually there is no reason why an interface could not define a contract that includes static methods.
For the current C# language implementation, the restriction is due to the allowance of inheritance of a base class and interfaces. If "class SomeBaseClass" implements "interface ISomeInterface" and "class SomeDerivedClass : SomeBaseClass, ISomeInterface" also implements the interface, a static method to implement an interface method would fail compile because a static method cannot have same signature as an instance method (which would be present in base class to implement the interface).
A static class is functionally identical to a singleton and serves the same purpose as a singleton with cleaner syntax. Since a singleton can implement an interface, interface implementations by statics are conceptually valid.
So it simply boils down to the limitation of C# name conflict for instance and static methods of the same name across inheritance. There is no reason why C# could not be "upgraded" to support static method contracts (interfaces).
An interface is an OOPS concept, which means every member of the interface should get used through an object or instance. Hence, an interface can not have static methods.
When a class implements an interface,it is creating instance for the interface members. While a static type doesnt have an instance,there is no point in having static signatures in an interface.