Is there a sane way in C# to achieve the following construct (in pseudocode):
void Method(MyClass<Attribute1, Attribute2, ...> foo)
{
// here I am guaranteed that foo has the specified attributes
}
Where Attribute* are, for example, enum values, such that only instances of MyClass instantiated with the attributes required by the method can be passed to the method (and otherwise fail to compile)?
I tried looking at generics since I know that C++ templates can make this work so it seemed like a logical starting point, but I couldn't get it working elegantly (I tried using interfaces to constrain the types of the parameter in this fashion but it was very bulky and frankly unusable since I have at least 4 attributes).
I want to do this to avoid having lots of annoying checks at the beginning of each method. I am doing DirectX 11 graphics development so I am kind of constrained by the API which does not make it particularly easy to pass objects around in this "type-safe" manner (in DirectX every resource has a large "Description" structure which contains information about what the resource can and cannot do, is and is not, etc.. and is tedious and error-prone to parse, so I am trying to write a wrapper around it for my and my users' convenience).
I also cannot have different class types for every case because there are a lot of combinations, so this seems like the most comfortable way to write code like this, and I am hoping C# makes this possible.
I'm sure there is a name for this kind of language feature (if you know it please let me know, I would have googled but this is kind of hard to search for when you don't know the proper keywords...)
Generic type parameters in .NET must be types themselves. You can't create a generic type/method that is specific to a particular value of the Generic type parameter only.
If you do not want or cannot create a type that represents the attribute values you want your method being restricted to, you will have to do sanity checks in your method to ensure that the proper attribute values are used in the provided "foo" object.
Using specific types as representation of specific attribute values might be an answer for the problem you asked about, but it has the disadvantage of not supporting switch-case statements (see further below). Please also read the final note at the end of my answer.
Say, you want a type that represents textures. Textures can have different number of channels, and different bit depths. You could then declare a generic texture type like this:
class Texture<TChannels, TBPC>
where TChannels : INumOfChannels,new()
where TBPC : IBitsPerChannel,new()
INumOfChannels and IBitsPerChannel are just interfaces and can be empty.
The new() constraint prevents creation of a concrete Texture type by using the interfaces themselves.
For different channels and different BPCs, you will create empty types extending from the respective base interfaces, for example:
class FourChannels : INumOfChannels {};
class ThreeChannels : INumOfChannels {};
class BitsPerChannel_24 : IBitsPerChannel {};
class BitsPerChannel_32 : IBitsPerChannel {};
Using this, you can restrict your generic method to certain attribute combinations. In case your method should only deal with 4-channel and 32bpc textures:
void MyMethod<TChannels, TBPC>(Texture<TChannels, TBPC> foo)
where TChannels : FourChannels
where TBPC : BitsPerChannel_32
Now, every good thing also has dark sides. How would you do something like this (written as pseudo-code)?
switch (NumOfChannelsAttribute)
{
case FourChannels:
// do something
break;
case ThreeChannels:
// do something else
break;
}
You can't, at least not in an easy and simple way, because "FourChannel" and "ThreeChannel" are types, not integral values.
Of course, you can still use if constructs. For this to work you would need to implement a property in the generic texture type which provides the used attributes:
class Texture<TChannels, TBPC> where TChannels : INumOfChannels,new() where TBPC : IBitsPerChannel,new()
{
public Type ChannelsAttribute
{
get { return typeof(TChannels); }
}
public Type BitsPerChannelAttribute
{
get { return typeof(TBPC); }
}
}
In an if construct, you could utilize this as follows:
var myTex = new Texture<FourChannels, BitsPerChannel_32>();
if (myTex.ChannelsAttribute == typeof(FourChannels))
{
... do something with 4 channels
}
else
{
... though luck, only 4 channels are supported...
}
A final note and advice:
While this might work for your problem, resorting to these kind of 'tricks' usually is an indication of a flawed design. I think it is well-invested time if you revisit the design choices you made in your code, so you don't need to rely on crutches like this.
C# doesn't have such a feature. You mention you have tried using interfaces, but don't specify how. The way I'd suggest you try using them is by using generics with multiple constraints, eg
void Method(T foo) where T : IAttribute1, IAttribute2, IAttribute3, IAttribute4
{
}
Let's say one such attribute class is then ICpuMappable, then you can constrain types that can be used with Method1 with:
void Method1(T foo) where T : ICpuMappable
{
}
and you can know any foo passed to Method1 is CPU mappable.
You'll likely end up with lots of interfaces, but as many will be treated as "flags", they shouldn't be too difficult to maintain.
Related
CUrrently in the process of finally learning C#. But after using C++ and python this is one thing that keeps striking me while writing C#.
C# doesn't have a similar thing to typedef in C++. (Or at least htat's true according to various posts here an other googling results.
Now the first use to "type alias" I can understand (though from experience disagree with - but that's something I can learn to accept).
However there is a different use I've gotten used to a lot, especially after using python for years:
The "Generic" pattern. Where I actually don't care about the type (and say I only care that it can be compared to each other). Now of course a generic class can "do" this, but quite often that is overkill: especially since classes typically have many of those, and they are of little importance to people who USE the class.
An example, say I have a dictionary, which binds "values" to certain "identifiers":
System.Collections.Generics.Dictionary<string, double>
Would be a logical start. However say in the future, when having a clearer picture of the whole application, I wish to change it up. I notice that for calculations I would actually need decimal values instead of floating point - (or maybe even bignums instead of floating points). I'd have to go over my whole code changing this.
Similar to the identifier: strings are "easy" but maybe in the future I don't really want to use such bloated structures. Rather I use something that "can be converted from strings and is unique enough" in my class
Or, hey, in a different future I might wish to not use the generic dictionary: rather I implement a custom one for this class specific.
All these things would require me to change code at many different places. Potential bug-heavy, and thus a maintainer would choose not to change it due to maintenance problems.
In other languages I learned this was solved either by "don't caring" (python) - or by allowing a typedef. And always using that typedef, also in other classes.
What is the idiomatic way to do this in C#? Is it generally accepted to use long "lists" of generic variables in your class definition?
MyClass<A_KeyType, A_ValueType, B_KeyType, B_ValueType, ContainerType>
Seems awkward since not the user, but the maintainer of the class might often know better which to use?
As a very simplistic (silly) example
public class MyClass {
public MyClass() { }
private Systems.Collections.Generics.Dictionary<string, double> Points = new Systems.Collections.Generics.Dictionary<string, double>()
Public void AddPerson(string studentID, double val) {
Points.Add(studentID, val)
}
}
getters, maybe changers etc would all have to explicitly refer to Systems.Collections.Generics.Dictionary<string, double>, even though maybe in the future a studentID would be a simple numeric value or something else. Also the code "using" this, which "gets" the student ID needs to understand it is a string.
In C++ I would parametrize the student type "under" the my class as:
public class MyClass {
typedef string StudentIDType
...
Then I would use that explicit type MyClass.StudentIDType in all situations.
C# doesn't have a similar thing to typedef in C++.
Typedef in C defines a new type. C# has type aliases:
using Frob = System.Collections.Dictionary<System.String, System.String>;
...
Frob f = new Frob();
But these are per file. The named alias is not a member of any namespace or type.
And C# of course allows you to define new types by wrapping old ones:
struct MyOpaqueIdentifier
{
private int id;
public MyOpaqueIdentifier(int id) { this.id = id; }
... now define equality, conversions, etc ...
}
However say in the future, when having a clearer picture of the whole application, I wish to change it up
This is the premature generality error, also known as YAGNI: You Ain't Gonna Need It. There are infinite ways to design programs to be more general, most of which you will never need. The right way to do it is to think hard about what kinds of generalities you're going to need up front, and design them in from the beginning.
Also, remember that Visual Studio has powerful refactoring tools.
What is the idiomatic way to do this in C#? Is it generally accepted to use long "lists" of generic variables in your class definition?
C# lets you express generality in several ways:
base classes -- I can accept anything derived from this class.
interfaces -- I can accept anything that implements this interface.
generics -- the type is parameterized by n other types
generic covariance and contravariance -- a sequence of turtles may be used where a sequence of animals is expected
generic constraints -- a type argument is constrained to a base type, interface, etc.
delegates -- needed functionality that consists of a single method (example: compare two Ts for equality) can be passed in as a delegate to that function, rather than requiring an interface, base type, etc.
It sounds to me like you are considering abusing generics; one of the other approaches is typically used.
Try something like this:
class Program
{
static void Main(string[] args)
{
var obj = new Class1<int, string>();
obj.Dictionary.Add(1, "hello");
}
}
class Class1<Tkey, Tvalue>
{
public Dictionary<Tkey, Tvalue> Dictionary { get; set; }
}
If you want Python way, then use Dictionary<string, object>
You will sacrifice performance and may run into a lot of runtime issues at the cost of minimizing code changes.
I really don't see any value in this. The maintainer still has to go to all the places where you have used float and replace all variable and inputs. You are kinda missing the point of using a strongly typed compiled language.
Your best bet is to create a generic class that wraps your functionality
class MyClass<T>
{
Dictionary<string, T> innerDict;
}
You seem to have a fundamental misunderstanding of generics in C#. They are not meant to allow for easy refactoring the way your C++ with typedef seems prepared for future maintainers to switch the type out. Such a usage seems wrong and, while I don't code in C++, I assume this is less used as a "generic" and more of an "anonymous class" definition. That is to say, you are actually defining a pseudoclass of type StudentIDType whose only property is a string value that you can access directly via the "alias". There are such a thing as anonymous classes in C# (see closures) but they are defined as the input for some function. Rather, the C# method of handling the above situation is to properly reify the pseudoclass to be an explicitly declared class. Such an implementation would look like this:
public class MyClass {
// DO NOT EVER DO THIS
// classes should not contain public classes this is merely the smallest possible example
public class StudentPoints {
public string StudentId { get; set; }
public double PointsValue { get; set; }
}
private IEnumerable<StudentPoints> StudentPointsList = new List<StudentPoints>();
public void AddPerson(StudentPoints studentPoints) {
this.StudentPointsList.Add(studentPoints);
}
}
However, there is an obvious problem with the above which should illustrate to you why the anonymous class is a bad idea. The first is that you've abandoned Dictionary for a simpler List/IEnumerable. This means you can't access values by key without "searching the list" (that is you no longer have a hash table implementation). The second is that you are still bound to change types when refactoring. Unless you can implicitly convert from one to another of the types you switch out then you will still have to change the constructors you use in your code to create StudentPoints. It is unavoidably true that changing the type of something will require code changes for most if not all references to that object. This is exactly what the refactoring tools in Visual Studio are built to help with. However, there is a pattern that you can use that is C# and would allow you to at least "reduce" the pain of the transition so that you don't have to find every instance in the code base before it will compile again. That pattern looks like this and utilizes overloads + the [Obsolete] parameter to indicate you are moving away from the old type and moving to the new:
public class MyClass {
private Dictionary<int, double> StudentPoints = new Dictionary<int, double>(); //was string, double
[Obsolete] // unfixed code will call this
public void AddPerson(string studentId, double val) {
int studentIdInt;
if (Int32.TryParse(studentId, out studentIdInt) {
this.AddPerson(studentIdInt, val);
return;
}
throw new ArgumentException(nameof(studentId), "string not convertable to int");
}
public void AddPerson(int studentId, double val) {
this.StudentList.Add(studentId, val);
}
}
Now the compiler will warn you instead of erroring when you pass a string instead. Issues here are that you may now get a runtime error for any string that isn't convertable to an int, something that would be a compile time error otherwise. Additionally this pattern (overload+obsolete attribute) could be used even with the first "reified" class as a constructor but my point is that you don't need to reify the class (in fact its unhelpful). Instead you should understand that yes, generics should declare their types as specifically as possible and yes, there are refactoring patterns that exist so that you can compile your code relatively quickly after changing the type for a generic but it comes with the trade of turning compile time errors into runtime errors. Hope that helps.
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 know that maybe this question has been asked before, but I can't seem to find a proper solution (having in mind that I am not a C# expert but a medium level user)...
I prepared a base class including an enum (AnimationStates) for animation states that my screen objects might have (for example a Soldier might have different states whereas a bird could have another set of states..) .. The base class is serving the purpose of storing update methods and other things for my animated screen objects (like animating all of them in the same manner)... The enum in the base class is (naturally) empty inside.. I have methods written utilizing the enum members...
If I define enum in my child classes by "public new enum...", I can "inherit" it.. right ? Moreover, and interestingly, I have a Dictionary in base class and I am trying to pass it from a child (i.e. soldier, or bird) to its base (animatedobject) class ... But I can't..
I feel I am doing something wrong or missing.. Any ideas ?
Well, you cannot do it directly with enums in C#.
I would propose taking more object-oriented approach, and replace the enums with real objects. This way you define an interface IAnimationState in your base class, and add an abstract method getAnimationState() as well. In the screen object classes you just implement this method, returning some specific implementation of the interface IAnimationState. This way you can put some logic into the small animation state classes, making your project more modular.
You can't expand enums. You can create new enums in derived classes but they're distinct.
I think you should just use int constants.
An enumerated type represents a simple set of values. That's it. You are trying to use an enum as a class type when it simply doesn't fit the bill.
Just create an enum (if you actually need to) and make a "real" type for the complex operations.
enum SomeEnum { Foo, Bar }
class Whatever
{
public SomeEnum { get { return SomeEnum.Foo; } }
}
This question is a good example of developing a solution without really understanding the problem. Instead of proposing your solution and asking us to figure out the last 20% that doesn't make any sense, tell us what you are actually trying to accomplish. Someone here may have a better approach that you haven't even thought of.
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.
I am still having trouble understanding what interfaces are good for. I read a few tutorials and I still don't know what they really are for other then "they make your classes keep promises" and "they help with multiple inheritance".
Thats about it. I still don't know when I would even use an interface in a real work example or even when to identify when to use it.
From my limited knowledge of interfaces they can help because if something implements it then you can just pass the interface in allowing to pass in like different classes without worrying about it not being the right parameter.
But I never know what the real point of this since they usually stop short at this point from showing what the code would do after it passes the interface and if they sort of do it it seems like they don't do anything useful that I could look at and go "wow they would help in a real world example".
So what I guess I am saying is I am trying to find a real world example where I can see interfaces in action.
I also don't understand that you can do like a reference to an object like this:
ICalculator myInterface = new JustSomeClass();
So now if I would go myInterface dot and intellisense would pull up I would only see the interface methods and not the other methods in JustSomeClass. So I don't see a point to this yet.
Also I started to do unit testing where they seem to love to use interfaces but I still don't understand why.
Like for instance this example:
public AuthenticationController(IFormsAuthentication formsAuth)
{
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
}
public class FormsAuthenticationWrapper : IFormsAuthentication
{
public void SetAuthCookie(string userName, bool createPersistentCookie)
{
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
public IFormsAuthentication FormsAuth
{
get;
set;
}
Like why bother making this interface? Why not just make FormsAuthenticationWrapper with the methods in it and call it a day? Why First make an interface then have the Wrapper implement the interface and then finally write the methods?
Then I don't get what the statement is really saying.
Like I now know that the statement is saying this
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
if formsAuth is null then make a new FormsAuthenticationWrapper and then assign it to the property that is an Interface.
I guess it goes back to the whole point of why the reference thing. Especially in this case since all the methods are exactly the same. The Wrapper does not have any new methods that the interface does not have and I am not sure but when you do this the methods are filled right(ie they have a body) they don't get converted to stubs because that would really seem pointless to me(it it would be converted back to an interface).
Then in the testing file they have:
var formsAuthenticationMock = new Mock<AuthenticationController.IFormsAuthentication>();
So they just pass in the FormsAuthentication what I am guessing makes all the fake stubs. I am guessing the wrapper class is used when the program is actually running since it has real methods that do something(like sign a person out).
But looking at new Mock(from moq) it accepts a class or an interface. Why not just again made the wrapper class put those methods in and then in the new Mock call that?
Would that not just make the stubs for you?
Ok, I had a hard time understanding too at first, so don't worry about it.
Think about this, if you have a class, that lets say is a video game character.
public class Character
{
}
Now say I want to have the Character have a weapon. I could use an interface to determin the methods required by a weapon:
interface IWeapon
{
public Use();
}
So lets give the Character a weapon:
public class Character
{
IWeapon weapon;
public void GiveWeapon(IWeapon weapon)
{
this.weapon = weapon;
}
public void UseWeapon()
{
weapon.Use();
}
}
Now we can create weapons that use the IWeapon interface and we can give them to any character class and that class can use the item.
public class Gun : IWeapon
{
public void Use()
{
Console.Writeline("Weapon Fired");
}
}
Then you can stick it together:
Character bob = new character();
Gun pistol = new Gun();
bob.GiveWeapon(pistol);
bob.UseWeapon();
Now this is a general example, but it gives a lot of power. You can read about this more if you look up the Strategy Pattern.
Interfaces define contracts.
In the example you provide, the ?? operator just provides a default value if you pass null to the constructor and doesn't really have anything to do with interfaces.
What is more relevant is that you might use an actual FormsAuthenticationWrapper object, but you can also implement your own IFormsAuthentication type that has nothing to do with the wrapper class at all. The interface tells you what methods and properties you need to implement to fulfill the contract, and allows the compiler to verify that your object really does honor that contract (to some extent - it's simple to honor a contract in name, but not in spirit), and so you don't have to use the pre-built FormsAuthenticationWrapper if you don't want to. You can build a different class that works completely differently but still honors the required contract.
In this respect interfaces are much like normal inheritance, with one important difference. In C# a class can only inherit from one type but can implement many interfaces. So interfaces allow you to fulfill multiple contracts in one class. An object can be an IFormsAuthentication object and also be something else, like IEnumerable.
Interfaces are even more useful when you look at it from the other direction: they allow you to treat many different types as if they were all the same. A good example of this is with the various collections classes. Take this code sample:
void OutputValues(string[] values)
{
foreach (string value in values)
{
Console.Writeline(value);
}
}
This accepts an array and outputs it to the console. Now apply this simple change to use an interface:
void OutputValues(IEnumerable<string> values)
{
foreach (string value in values)
{
Console.Writeline(value);
}
}
This code still takes an array and outputs it to the console. But it also takes a List<string> or anything else you care to give it that implements IEnumerable<string>. So we've taken an interface and used it to make a simple block of code much more powerful.
Another good example is the ASP.Net membership provider. You tell ASP.Net that you honor the membership contract by implementing the required interfaces. Now you can easily customize the built-in ASP.Net authentication to use any source, and all thanks to interfaces. The data providers in the System.Data namespace work in a similar fashion.
One final note: when I see an interface with a "default" wrapper implementation like that, I consider it a bit of an anit-pattern, or at least a code smell. It indicates to me that maybe the interface is too complicated, and you either need to split it apart or consider using some combination of composition + events + delegates rather than derivation to accomplish the same thing.
Perhaps the best way to get a good understanding of interfaces is to use an example from the .NET framework.
Consider the following function:
void printValues(IEnumerable sequence)
{
foreach (var value in sequence)
Console.WriteLine(value);
}
Now I could have written this function to accept a List<T>, object[], or any other type of concrete sequence. But since I have written this function to accept a parameter of type IEnumerable that means that I can pass any concrete type into this function that implements the IEnumerable interface.
The reason this is desirable is that by using the interface type your function is more flexible than it would otherwise be. Also you are increasing the utility of this function as many different callers will be able to make use of it without requiring modification.
By using an interface type you are able to declare the type of your parameter as a contract of what you need from whatever concrete type is passed in. In my example I don't care what type you pass me, I just care that I can iterate it.
All of the answers here have been helpful and I doubt I can add anything new to the mix but in reading the answers here, two of the concepts mentioned in two different answers really meshed well in my head so I will compose my understanding here in the hopes that it might help you.
A class has methods and properties and each of the methods and properties of a class has a signature and a body
public int Add(int x, int y)
{
return x + y;
}
The signature of the Add method is everything before the first curly brace character
public int Add(int x, int y)
The purpose of the method signature is to assign a name to a method and also to describe it's protection level (public, protected, internal, private and / or virtual) which defines where a method can be accessed from in code
The signature also defines the type of the value returned by the method, the Add method above returns an int, and the arguments a method expects to have passed to it by callers
Methods are generally considered to be something an object can do, the example above implies that the class the method is defined in works with numbers
The method body describes precisly (in code) how it is that an object performs the action described by the method name. In the example above the add method works by applying the addition operator to it's parameters and returing the result.
One of the primary differences between an interface and a class in terms of language syntax is that an interface can only define the signature of a methd, never the method body.
Put another way, an interface can describe in a the actions (methods) of a class, but it must never describe how an action is to be performed.
Now that you hopefully have a better understanding of what an interface is, we can move on to the second and third parts of your question when, and why would we use an interface in a real program.
One of the main times interfaces are used in a program is when one wants to perform an action, without wanting to know, or be tied to the specifics of how those actions are performed.
That is a very abstract concept to grapsp so perhaps an example might help to firm things up in your mind
Imagine you are the author of a very popular web browser that millions of people use every day and you have thousands of feature requests from people, some big, some little, some good and some like "bring back <maquee> and <blink> support".
Because you only have a relitivly small number of developers, and an even smaller number of hours in the day, you can't possibly implement every requested feature yourself, but you still want to satisfy your customers
So you decide to allow users to develop their own plugins, so they can <blink 'till the cows come home.
To implement this you might come up with a plugin class that looks like:
public class Plugin
{
public void Run (PluginHost browser)
{
//do stuff here....
}
}
But how could you reasonably implement that method? You can't possibly know precisly how every poossible future plugin is going to work
One possible way around this is to define Plugin as an interface and have the browser refer to each plugin using that, like this:
public interface IPlugin
{
void Run(PluginHost browser);
}
public class PluginHost
{
public void RunPlugins (IPlugin[] plugins)
{
foreach plugin in plugins
{
plugin.Run(this);
}
}
}
Note that as discussed earlier the IPlugin interface describes the Run method but does not specify how Run does it's job because this is specific to each plugin, we don't want the plugin host concerned with the specifics of each individual plugin.
To demonstrate the "can-be-a" aspect of the relationship between a class and an interface I will write a plugin for the plugin host below that implements the <blink> tag.
public class BlinkPlugin: IPlugin
{
private void MakeTextBlink(string text)
{
//code to make text blink.
}
public void Run(PluginHost browser)
{
MakeTextBlink(browser.CurrentPage.ParsedHtml);
}
}
From this perspective you can see that the plugin is defined in a class named BlinkPlugin but because it also implements the IPlugin interface it can also be refered to as an IPlugin object,as the PluginHost class above does, because it doesn't know or care what type the class actually is, just that it can be an IPlugin
I hope this has helped, I really didnt intend it to be quite this long.
I'll give you an example below but let me start with one of your statements. "I don't know how to identify when to use one". to put it on edge. You don't need to identify when to use it but when not to use it. Any parameter (at least to public methods), any (public) property (and personally I would actually extend the list to and anything else) should be declared as something of an interface not a specific class. The only time I would ever declare something of a specific type would be when there was no suitable interface.
I'd go
IEnumerable<T> sequence;
when ever I can and hardly ever (the only case I can think off is if I really needed the ForEach method)
List<T> sequence;
and now an example. Let's say you are building a sytem that can compare prices on cars and computers. Each is displayed in a list.
The car prices are datamined from a set of websites and the computer prices from a set of services.
a solution could be:
create one web page, say with a datagrid and Dependency Injection of a IDataRetriever
(where IDataRetriver is some interface making data fetching available with out you having to know where the data came from (DB,XML,web services or ...) or how they were fetched (data mined, SQL Quering in house data or read from file).
Since the two scenarios we have have nothing but the usage in common a super class will make little sense. but the page using our two classes (one for cars and one for computers) needs to perform the exact same operations in both cases to make that possible we need to tell the page (compiler) which operations are possible. We do that by means of an interface and then the two classes implement that interfcae.
using dependency injection has nothing to do with when or how to use interfaces but the reason why I included it is another common scenario where interfaces makes you life easier. Testing. if you use injection and interfaces you can easily substitute a production class for a testing class when testing. (This again could be to switch data stores or to enforce an error that might be very hard to produce in release code, say a race condition)
We use interfaces (or abstract base classes) to allow polymorphism, which is a very central concept in object-oriented programming. It allows us to compose behavior in very flexible ways. If you haven't already, you should read Design Patterns - it contains numerous examples of using interfaces.
In relation to Test Doubles (such as Mock objects), we use interfaces to be able to remove functionality that we currently don't want to test, or that can't work from within a unit testing framework.
Particularly when working with web development, a lot of the services that we rely on (such as the HTTP Context) isn't available when the code executes outside of the web context, but if we hide that functionality behind an interface, we can replace it with something else during testing.
The way I understood it was:
Derivation is 'is-a' relationship e.g., A Dog is an Animal, A Cow is an Animal but an interface is never derived, it is implemented.
So, interface is a 'can-be' relationship e.g., A Dog can be a Spy Dog, A Dog can be a Circus Dog etc. But to achieve this, a dog has to learn some specific things. Which in OO terminology means that your class has to able to do some specific things (contract as they call it) if it implements an interface. e.g., if your class implements IEnumerable, it clearly means that your class has (must have) such a functionality that it's objects can be Enumerated.
So, in essence, through Interface Implementation a Class exposes a functionality to its users that it can do something and it is NOT inheritance.
With almost everything written about interfaces, let me have a shot.
In simple terms, interface is something which will relate two or more , otherwise, non related classes.
Interfaces define contract which ensures that any two or more classes, even if not completely related, happens to implement a common interface, will contain a common set of operations.
Combined with the support of polymorphism , one can use interfaces to write cleaner and dynamic code.
eg.
Interface livingBeings
-- speak() // says anybody who IS a livingBeing need to define how they speak
class dog implements livingBeings
--speak(){bark;} // implementation of speak as a dog
class bird implements livingBeings
--speak(){chirp;}// implementation of speak as a bird
ICalculator myInterface = new JustSomeClass();
JustSomeClass myObject = (JustSomeClass) myInterface;
Now you have both "interfaces" to work with on the object.
I am pretty new to this too, but I like to think of interfaces as buttons on a remote control. When using the ICalculator interface, you only have access to the buttons (functionality) intended by the interface designer. When using the JustSomeClass object reference, you have another set of buttons. But they both point to the same object.
There are many reasons to do this. The one that has been most useful to me is communication between co-workers. If they can agree on an interface (buttons which will be pushed), then one developer can work on implementing the button's functionality and another can write code that uses the buttons.
Hope this helps.