Related
Recently I was implementing a Trie data structure and decided the Nodes could store different types of data or have its implementation varied so then I went for Node<T>. Then as I got into the algorithm for constructing the Trie I realised it required more intimate knowledge of the Node so I constrained the generic class to use an INode interface. This allows for more flexibility but felt wrong in the context of a generic class.
Generic classes have a different use case to classes which implement an interface. For example, List<T> - the algorithm can work without being dependent on a related set of abstractions. A class which implements an interface may require polymorphism/DI but the interfaces will be more specialized.
Under what circumstances do others apply a generic class T where T may implement a more specialized interface?
I thought that a generic class is used when T does not really need to expose operations/data though I can see a generic class may be used where T implements IDisposable or some other more general interface.
Any help in clarifying these points?
When faced with a choice to use a generic with an interface constraint vs. a non-generic with an interface type, I would go for generic+interface only in situations when some or all of types passed as generic arguments are value types. This would prevent my implementation from requiring costly boxing and unboxing when dealing with my structs.
For example, if the interface happens to be IComparable, I wold definitely prefer a generic with a constraint, because it would let me avoid boxing when working with primitives.
Note that an alternative way of providing functionality to your generic class is passing a delegate along with the value. For example, if you plan to do something like this
interface IScoreable {
decimal GetScore(object context);
}
class Node<T> where T : IScoreable {
...
void DoSomething(T data) {
var score = data.GetScore(someContext);
...
}
}
you can also do this:
class Node<T> {
private Func<T,object,decimal> scorer;
public Node(Func<T,object,decimal> scorer) {
this.scorer = scorer;
}
...
void DoSomething(T data) {
var score = scorer(data, someContext);
...
}
}
The second solution lets you "decouple" the scoring functionality from the type being scored, at the expense of having the caller to write a little more code.
I see nothing wrong with placing constraints on the generic argument. Having a generic argument does not imply "this will work for anything", it implies that there is more than one way that the code will make sense.
It might actually expose a completely generic concept, like List<T>, but it might expose a concept that makes sense only in some contexts (like Nullable<T> only making sense for non-nullable entities)
The constraints are just that mechanism that you use to tell the world under what circumstances the class will make sense, and will enable you to actually use that (constrained) argument in a reasonable way, i.e. calling Dispose on things that implement IDisposable
The extreme of this is when the context is very constrained, i.e. what if there are only two possible implementations? I actually have that case in my current codebase, and I use generics. I need some processing done on some data point, and currently (and in the foreseeable future) there are only two kinds of data points. This is, in principle, the code I use:
interface IDataPoint
{
SomeResultType Process();
}
class FirstKindDataPoint : IDataPoint
{
SomeResultType Process(){...}
};
class SecondKindDataPoint : IDataPoint
{
SomeResultType Process(){...}
};
class DataPointProcessor<T> where T: IDataPoint
{
void AcquireAndProcessDataPoints(){...}
}
It makes sense, even in this constrained context, because I have only one processor, so only one logic to take care of, instead of two separate processor that I will have to try to keep in sync.
This way I can have a List<T> and an Action<T> within the processor instead of a List<IDataPoint> and Action<IDataPoint> which will be incorrect in my scenario, as I need a processor for a more specific data type, that is still, implementing IDataPoint.
If I needed a processor that will process anything, as long as it is an IDataPoint, it might make sense to remove the its genericity, and simply use IDataPoint within the code.
Additionally, the point raised in #dasblinkenlight's answer is very valid. If the generic parameters can be both structs and classes than using generics will avoid any boxing.
Generics are usually used where using an interface or a base class (and this includes object) are not enough, for example where you are worried about the return value's of your function being the original type rather than just the interface, or where the parameters you are passing in may be expressions that operate on the specific type.
So if you approach the logic from the other end. The decisions on type restrictions should be the same decision as when you are choosing the types of your function parameters.
So I've got a generic class called VariableSeries, an abstract class called Indicator derived from it, and then various classes (let's call them indicators) that implement that abstract class. I want to have a List of indicators and be able to use it.
public class VariableSeries<T>
{
protected List<T> Series;
public int CurrentBar { get; private set; }
public T this[int index]
{
get
{
if (index > CurrentBar)
throw new Exception("Tried to look too far in the past, data does not exist.");
return Series[CurrentBar - index];
}
}
...
}
And I've got an Indicator class that's derived from VariableSeries:
public abstract class Indicator<T> : VariableSeries<T>
{
...
}
Now I want to have a List of indicators of various types. My first idea was to just declare a List, but that doesn't really work. And I can't just throw an interface at it and cast to that, because I need to use the indexation, which makes use of the generic type.
So let's say I've got the following indicator (one of many):
public class MovingAverage<T> : Indicator<double>
{
...
}
Is there any way to do the following:
List<???> Indicators = new List<???>();
Indicators.Add(new MovingAverage<type is provided dynamically>());
do stuff with Indicators[0][0];
Perhaps some sort of way of casting to a generic class without having to specify the type, like ((VariableSeries<>)Indicators[0])[0]?
The ??? in your List<???> must be a concrete type. This concrete type must, in your case, a commonly shared basetype or interface.
All your classes share a basetype VariableSeries<T> but this one is not concrete / specific. So List<VariableSeries<T>> is not possible.
If all your indicaters would use the generic type double, than you could use List<VariableSeries<double>>, but I am afraid that is not the case.
The question is: what are your going to do with that list? Iterate through them and then what? Ask for their value? What value? What type? A double? A string? The compiler cannot know!
One solution could be to create an interface like this:
public interface IVariableSeries
{
object this[int index] { get; }
}
Implement this interface EXPLICITLY in your VariableSeries<T> and use this interface as your concrete type in your list: List<IVariableSeries>.
You can make the abstract class implement an interface with all methods that will be common to all classes and has no type parameters.
class VariableSeries<T> : IUntypedInterface
Then you can use a List<IUntypedInterface> to get then all together.
You can do some stuff using reflection. For example you can create a MovingAverage with a dynamic T using the following:
Type dynamicType = typeof(int); // or any other, e.g. user selected type
var instance = (dynamic)Activator.CreateInstance(typeof(MovingAverage<>).CreateGenericType(dynamicType));
The problem of course is that you don't know the type of instance at compile time. Thus you can't call any methods on it and you can't cast it of course the type isn't known at compile time. That's why I wrapped it as dynamic. You can call any method and it will in the background reflect into that type and look for the method signature that you called.
You can check if instance is a MovingAverage<> by doing
typeof(MovingAverage<>).Equals(instance.GetType().GetGenericTypeDefinition())
Be aware that this will return false when instance is actually of a derived type of MovingAverage. You can also check that, but it's a bit more complicated.
Going the dynamic route is of course a dangerous path in a language that otherwise relies so much on static type checking. You won't have refactoring support and you will have to test a lot running your code. A single typo and your program will throw an exception.
Also, I would suggest you get familiar with .Net reflection. You're entering a dangerous world.
Add a generic method and pass the type to that method. this code will go in generic method.
List Indicators = new List();
Indicators.Add(new MovingAverage());
We recently learned about generic classes in C#, but our teacher failed to mention what they can be used for. I can't really find any good examples and would be extremly happy if somebody help me out :)
Have you made your own generic class, and what did you use it for?
Some code examples would make me, and my classmates, really happy! Pardon the bad english, I am from sweden :)
happy programming!
Sorry- I think I could have written the question a bit better. I am familar with generic collections. I just wondered what your own generic classes can be used for.
and thank you for the MSDN links, I did read them before posting the question, but maybe I missed something? I will have a second look!
Generic Collections
Generics for collections are very useful because they allow compile time type safety. This is useful for a few reasons:
No casting is required when retreiving values. This is not only a performance benefit but also eliminates the risk of there being a casting exception at runtime
When value types are added to a non generic list such as an ArrayList, the value's have to be boxed. This means that they are stored as reference types. It also means that not only does the value get stored in memory, but so does a reference to it, so more memory than necessery is used. This problem is eliminated when using generic lists.
Generic Classes
Generic classes can be useful for reusing common code for different types. Take for example a simple non generic factory class:
public class CatFactory
{
public Cat CreateCat()
{
return new Cat();
}
}
I can use a generic class to provide a factory for (almost) any type:
public class Factory<T> where T : new()
{
public T Create()
{
return new T();
}
}
In this example I have placed a generic type constraint of new() on the type paramter T. This requires the generic type to contain a parameterless contructor which enables me to create an instance without knowing the type.
Just because you said you are Swedish, I thought I'd give an example integrating IKEA furniture. Your kit couches are an infestation in north america, so I thought I'd give something back :) Imagine a class which represents a particular kit for building chairs and tables. To remain authentic, I'll even use nonsense swedish linguistic homonyms:
// interface for included tools to build your furniture
public interface IToolKit {
string[] GetTools();
}
// interface for included parts for your furniture
public interface IParts {
string[] GetParts();
}
// represents a generic base class for IKEA furniture kit
public abstract class IkeaKit<TContents> where TContents : IToolKit, IParts, new() {
public abstract string Title {
get;
}
public abstract string Colour {
get;
}
public void GetInventory() {
// generic constraint new() lets me do this
var contents = new TContents();
foreach (string tool in contents.GetTools()) {
Console.WriteLine("Tool: {0}", tool);
}
foreach (string part in contents.GetParts()) {
Console.WriteLine("Part: {0}", part);
}
}
}
// describes a chair
public class Chair : IToolKit, IParts {
public string[] GetTools() {
return new string[] { "Screwdriver", "Allen Key" };
}
public string[] GetParts() {
return new string[] {
"leg", "leg", "leg", "seat", "back", "bag of screws" };
}
}
// describes a chair kit call "Fnood" which is cyan in colour.
public class Fnood : IkeaKit<Chair> {
public override string Title {
get { return "Fnood"; }
}
public override string Colour {
get { return "Cyan"; }
}
}
public class Snoolma : IkeaKit<Chair> {
public override string Title {
get { return "Snoolma "; }
}
public override string Colour {
get { return "Orange"; }
}
}
Ok, so now we've got all the bits we need to figure out how to build some cheap furniture:
var fnood = new Fnood();
fnood.GetInventory(); // print out tools and components for a fnood chair!
(Yes, the lack of instructions and the three legs in the chair kit is deliberate.)
Hope this helps in a cheeky way.
If one has a List object (non-generic), one can store into it anything that can be cast into Object, but there's no way of knowing at compile time what type of things one will get out of it. By contrast, if one has a generic List<Animal>, the only things one can store into it are Animal or derivatives thereof, and the compiler can know that the only things that will be pulled out of it will be Animal. The compiler can thus allow things to be pulled out of the List and stored directly into fields of type Animal without any need for run-time type checking.
Additionally, if the generic type parameter of a generic class happens to be a value type, use of generic types can eliminate the need for casting to and from Object, a process called "Boxing" which converts value-type entities into reference-type objects; boxing is somewhat slow, and can sometimes alter the semantics of value-type objects, and is thus best avoided when possible.
Note that even though an object of type SomeDerivedClass may be substitutable for TheBaseClass, in general, a GenericSomething<SomeDerivedClass> is not substitutable for a GenericSomething<TheBaseClass>. The problem is that if one could substitute e.g. a List<Giraffe> for a List<Zebra>, one could pass a List<Zebra> to a routine that was expecting to take a List<Giraffe> and store an Elephant in it. There are a couple of cases where substitutability is permitted, though:
Arrays of a derived type may be passed to routines expecting arrays of base type, provided that those routines don't try to store into those arrays any items that are not of the proper derived type.
Interfaces may be declared to have "out" type parameters, if the only thing those interfaces will do is return ("output") values of that type. A Giraffe-supplier may be substituted for an Animal-supplier, because all it's going to do is supply Giraffes, which are in turn substitutable for animals. Such interfaces are "covariant" with respect to those parameters.
In addition, it's possible to declare interfaces to declare "in" type parameters, if the only thing the interfaces do is accept parameters of that type by value. An Animal-eater may be substituted a Giraffe-eater, because--being capable of eating all Animals, it is consequently capable of eating all Giraffes. Such interfaces are "contravariant" with respect to those parameters.
The most common example is for collections such as List, Dictionary, etc. All those standard classes are implemented using generics.
Another use is to write more general utility classes or methods for operations such as sorting and comparisons.
Here is a Microsoft article that can be of help: http://msdn.microsoft.com/en-us/library/b5bx6xee%28v=vs.80%29.aspx
The largest benefit that I've seen is the compile-time safety of generics, as #Charlie mentioned. I've also used a generic class to implement a DataReader for bulk inserts into a database.
Well, you have a lot of samples inside the framework. Imagine that you need to implement a list of intergers, and later a list of strings... and later a list of you customer class... etc. It would be very painfull.
But, if you implements a generic list the problem is solved in less time, in less code and you only have to test one class.
Maybe one day you will need to implement your own queue, with rules about the priority of every element. Then, it would be a good idea to make this queue generic if it is possible.
This is a very easy sample, but as you improve your coding skills, you will see how usefull can be to have (for example) a generic repository (It's a design patters).
Not everyday programmers make generic classes, but trust me, you will be happy to count with such tool when you need it.
real world example for generics.
Think u have a cage where there are many different birds(parrot,pegion,sparrow,crow,duck) in it(non generic).
Now you are assigned a work to move the bird to seperate cages(specifically built for single bird) from the cage specified above.
(problem with the non generic list)
It is a tedious task to catch the specific bird from the old cage and to shift it to the cage made for it.(Which Type of bird to which cage --Type casting in c#)
generic list
Now think you have a seperate cage for seperate bird and you want to shift to other cages made for it. This will be a easy task and it wont take time for you to do it(No type casting required-- I mean mapping the birds with cages).
My friend is not a programmer and I would like to explain what is generics? I would explain him generics as below. Thus this is a real-world scenario of using generics.
"There is this manufacturer in the next street. He can manufacture any automobile. But at one instance he can manufacture only one type of automobile. Last week, he manufactured a CAR for me, This week he manufactured a TRUCK for my uncle. Like I said this manufacturing unit is so generic that it can manufacture what the customer specifies. But note that when you go to approach this manufacturer, you must go with a type of automobile you need. Otherwise approaching him is simply not possible."
Have a look at this article by Microsoft. You have a nice and clear explanation of what to use them for and when to use them. http://msdn.microsoft.com/en-us/library/ms172192.aspx
The various generic collections are the best example of generics usage but if you want an example you might generate yourself you could take a look at my anwer to this old question:
uses of delegates in c or other languages
Not sure if it's a particularly great example of generics usage but it's something I find myself doing on occasion.
Are you talking about a base class (or perhaps an abstract class)? As a class that you would build other classes (subclasses) off of?
If that's the case, then you'd create a base class to include methods and properties that will be common to the classes that inherit it. For example, a car class would include wheels, engine, doors, etc. Then maybe you'd maybe create a sportsCar subclass that inherits the car class and adds properties such as spoiler, turboCharger, etc.
http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)
enter link description here
It's hard to understand what you mean by "generic class" without some context.
I have a situation where I would like to have objects of a certain type be able to be used as two different types. If one of the "base" types was an interface this wouldn't be an issue, but in my case it is preferable that they both be concrete types.
I am considering adding copies of the methods and properties of one of the base types to the derived type, and adding an implicit conversion from the derived type to that base type. Then users will be able treat the derived type as the base type by using the duplicated methods directly, by assigning it to a variable of the base type, or by passing it to a method that takes the base type.
It seems like this solution will fit my needs well, but am I missing anything? Is there a situation where this won't work, or where it is likely to add confusion instead of simplicity when using the API?
EDIT: More details about my specific scenario:
This is for a potential future redesign of the way indicators are written in RightEdge, which is an automated trading system development environment. Price data is represented as a series of bars, which have values for the open, low, high, and close prices for a given period (1 minute, 1 day, etc). Indicators perform calculations on series of data. An example of a simple indicator is the moving average indicator, which gives the moving average of the most recent n values of its input, where n is user-specified. The moving average might be applied to the bar close, or it could be applied to the output of another indicator to smooth it out.
Each time a new bar comes in, the indicators compute the new value for their output for that bar.
Most indicators have only one output series, but sometimes it is convenient to have more than one output (see MACD), and I want to support this.
So, indicators need to derive from a "Component" class which has the methods that are called when new data comes in. However, for indicators which have only one output series (and this is most of them), it would be good for them to act as a series themselves. That way, users can use SMA.Current for the current value of an SMA, instead of having to use SMA.Output.Current. Likewise, Indicator2.Input = Indicator1; is preferable to Indicator2.Input = Indicator1.Output;. This may not seem like much of a difference, but a lot of our target customers are not professional .NET developers so I want to make this as easy as possible.
My idea is to have an implicit conversion from the indicator to its output series for indicators that have only one output series.
You don't provide too many details, so here is an attempt to answering from what you provide.
Take a look at the basic differences:
When you have a base type B and a derived type D, an assignment like this:
B my_B_object = my_D_object;
assigns a reference to the same object. On the other hand, when B and D are independent types with an implicit conversion between them, the above assignment would create a copy of my_D_object and store it (or a reference to it if B is a class) on my_B_object.
In summary, with "real" inheritance works by reference (changes to a reference affect the object shared by many references), while custom type conversions generally work by value (that depends on how you implement it, but implementing something close to "by reference" behavior for converters would be nearly insane): each reference will point to its own object.
You say you don't want to use interfaces, but why? Using the combo interface + helper class + extension methods (C# 3.0 and .Net 3.5 or newer required) can get quite close to real multiple inheritance. Look at this:
interface MyType { ... }
static class MyTypeHelper {
public static void MyMethod(this MyType value) {...}
}
Doing that for each "base" type would allow you to provide default implementations for the methods you want to.
These won't behave as virtual methods out-of-the-box; but you may use reflection to achieve that; you would need to do the following from within the implementation on the Helper class:
retrieve a System.Type with value.GetType()
find if that type has a method matching the signature
if you find a matching method, invoke it and return (so the rest of the Helper's method is not run).
Finally, if you found no specific implementation, let the rest of the method run and work as a "base class implementation".
There you go: multiple inheritance in C#, with the only caveat of requiring some ugly code in the base classes that will support this, and some overhead due to reflection; but unless your application is working under heavy pressure this should do the trick.
So, once again, why you don't want to use interfaces? If the only reason is their inability to provide method implementations, the trick above solves it. If you have any other issue with interfaces, I might try to sort them out, but I'd have to know about them first ;)
Hope this helps.
[EDIT: Addition based on the comments]
I've added a bunch of details to the original question. I don't want to use interfaces because I want to prevent users from shooting themselves in the foot by implementing them incorrectly, or accidentally calling a method (ie NewBar) which they need to override if they want to implement an indicator, but which they should never need to call directly.
I've looked at your updated question, but the comment quite summarizes it. Maybe I'm missing something, but interfaces + extensions + reflection can solve everything multiple inheritance could, and fares far better than implicit conversions at the task:
Virtual method behavior (an implementation is provided, inheritors can override): include method on the helper (wrapped in the reflection "virtualization" described above), don't declare on the interface.
Abstract method behavior (no implementation provided, inheritors must implement): declare method on the interface, don't include it on the helper.
Non-virtual method behavior (an implementation is provided, inheritors may hide but can't override): Just implement it as normal on the helper.
Bonus: weird method (an implementation is provided, but inheritors must implement anyway; they may explicitly invoke the base implementation): that's not doable with normal or multiple inheritance, but I'm including it for completeness: that's what you'd get if you provide an implementation on the helper and also declare it on the interface. I'm not sure of how would that work (on the aspect of virtual vs. non-virtual) or what use it'd have, but hey, my solution has already beaten multiple inheritance :P
Note: On the case of the non-virtual method, you'd need to have the interface type as the "declared" type to ensure that the base implementation is used. That's exactly the same as when an inheritor hides a method.
I want to prevent users from shooting themselves in the foot by implementing them incorrectly
Seems that non-virtual (implemented only on the helper) will work best here.
or accidentally calling a method (ie NewBar) which they need to override if they want to implement an indicator
That's where abstract methods (or interfaces, which are a kind of super-abstract thing) shine most. The inheritor must implement the method, or the code won't even compile. On some cases virtual methods may do (if you have a generic base implementation but more specific implementations are reasonable).
but which they should never need to call directly
If a method (or any other member) is exposed to client code but shouldn't be called from client code, there is no programmatic solution to enforce that (actually, there is, bear with me). The right place to address that is on the documentation. Because you are documenting you API, aren't you? ;) Neither conversions nor multiple inheritance could help you here. However, reflection may help:
if(System.Reflection.Assembly.GetCallingAssembly()!=System.Reflection.Assembly.GetExecutingAssembly())
throw new Exception("Don't call me. Don't call me!. DON'T CALL ME!!!");
Of course, you may shorten that if you have a using System.Reflection; statement on your file. And, BTW, feel free to change the Exception's type and message to something more descriptive ;).
I see two issues:
User-defined type conversion operators are generally not very discoverable -- they don't show up in IntelliSense.
With an implicit user-defined type conversion operator, it's often not obvious when the operator is applied.
This doesn't been you shouldn't be defining type conversion operators at all, but you have to keep this in mind when designing your solution.
An easily discoverable, easily recognizable solution would be to define explicit conversion methods:
class Person { }
abstract class Student : Person
{
public abstract decimal Wage { get; }
}
abstract class Musician : Person
{
public abstract decimal Wage { get; }
}
class StudentMusician : Person
{
public decimal MusicianWage { get { return 10; } }
public decimal StudentWage { get { return 8; } }
public Musician AsMusician() { return new MusicianFacade(this); }
public Student AsStudent() { return new StudentFacade(this); }
}
Usage:
void PayMusician(Musician musician) { GiveMoney(musician, musician.Wage); }
void PayStudent(Student student) { GiveMoney(student, student.Wage); }
StudentMusician alice;
PayStudent(alice.AsStudent());
It doesn't sound as if your method would support a cross-cast. True multiple inheritance would.
An example from C++, which has multiple inheritance:
class A {};
class B {};
class C : public A, public B {};
C o;
B* pB = &o;
A* pA = dynamic_cast<A*>(pB); // with true MI, this succeeds
Then users will be able treat the derived type as the base type by using the duplicated methods directly, by assigning it to a variable of the base type, or by passing it to a method that takes the base type.
This will behave differently, however. In the case of inheritance, you're just passing your object. However, by implementing an implicit converter, you'll always be constructing a new object when the conversion takes place. This could be very unexpected, since it will behave quite differently in the two cases.
Personally, I'd make this a method that returns the new type, since it would make the actual implementation obvious to the end user.
Maybe I'm going too far off with this, but your use case sounds suspiciously as if it could heavily benefit from building on Rx (Rx in 15 Minutes).
Rx is a framework for working with objects that produce values. It allows such objects to be composed in a very expressive way and to transform, filter and aggregate such streams of produced values.
You say you have a bar:
class Bar
{
double Open { get; }
double Low { get; }
double High { get; }
double Close { get; }
}
A series is an object that produces bars:
class Series : IObservable<Bar>
{
// ...
}
A moving average indicator is an object that produces the average of the last count bars whenever a new bar is produced:
static class IndicatorExtensions
{
public static IObservable<double> MovingAverage(
this IObservable<Bar> source,
int count)
{
// ...
}
}
The usage would be as follows:
Series series = GetSeries();
series.MovingAverage(20).Subscribe(average =>
{
txtCurrentAverage.Text = average.ToString();
});
An indicator with multiple outputs is similar to GroupBy.
This might be a stupid idea, but: if your design requires multiple inheritance, then why don't you simply use a language with MI? There are several .NET languages which support multiple inheritance. Off the top of my head: Eiffel, Python, Ioke. There's probable more.
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.