Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How an Interface like IEnumerable or IQuerable can store data into itself?
or for example where this Tables go on `IQueryable?
and How can I have an Interface like that for myself ?
public Interface IMyNumerator<T>
{
}
IMyNumerator<int> mynumbers;
how can I fill mynumbers with some Int values ??
The interfaces themselves do not contain data. Although you may see IEnumerable as a type when using a collection, the underlying object is always of a specific type implementing this interface.
The object actually containing your data may be of any type implementing that interface.
Please refer to:
IEnumerable interface
List implementation
And if you would like to implement your own version of IEnumerable, inherit from the interface . Try searching for "A Beginners Tutorial on Implementing IEnumerable" on codeproject ;-)
An interface never stores data. An implementation does. Whenever your code sees an object of type IEnumerable, its actual dynamic type is something else, like a ListIterator or so. If you want to have your own type implement IEnumerable you can just do that. Usually, you'll have an embedded (private) class that implements the enumerator for a collection, though.
Interfaces define, well interfaces.
You can see it as defining a Contract, that explains how to work with a specific concept. Behind the interface is an actual Implementation, for example a Database Connection.
In computer science, an interface is the point of interaction with software
To make it a bit more simple, consider this in the hardware world.
USB defines an interface to things, it has a specific shape so it can go into a specific plug, and it has "protocols" of how to talk with a USB device.
An behind this "interface" you can have, just about any device. Fx. a camera or a storage device.
Well this is a very confusing question but I'll try anyway.
IEnumerable is an Interface that only describes public methods / properties, it does not describe how data is stored.
The implementer of this interface is responsible to store the data and can do so in any structure that suits the need.
You can have an interface like that by yourself by either implemented it or defining another interface that you use.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
We are about to start a project right from scratch. As per the design discussions i am thinking to bring this topic.
Most of the times,I have seen that Abstract classes were being used just to provide some default/common behavior with some concrete methods.
So, i thought of defining those concrete methods as Extension methods for the Interface i am going to develop in place of Abstract classes.
Can someone guide me regarding my design decision. If you are not going to agree with my point please justify your argument with possible scenario/issues which we can face in case of doing so. So, that it will improve my knowledge.
Both approaches are very very different.
Using an abstract class and though abstract/virtual methods, you allow the derived classes to override a behavior which is not the case for extension method. Extension methods are extensions at the end of the day, they are not part of the type and are hard to spot when someone is examining the API and the features the type provides.
Second point, creating an extension method for a type that you create yourself is not that logical IMHO. Using a base Abstract class keeps your hierarchy clear and keeps your model open for modifications of overridden behaviors.
Extension methods were introduced in C# because a very particular requirement.
When they were designing LINQ they realized that they wouldn't want to create a new interface which would contain all known LINQ methods like Where or Select, because it would mean that any enumerable or collection implementation would need to implement it.
Above mentioned fact has an important drawback: it would need to extensively change the source code of a lot of classes from the Base Class Library and any third-party library or project implementing custom collections couldn't take advantage of LINQ at all.
Then they thought about an approach that could directly work with iterators (i.e. IEnumerator<T>) and that could be compatible with any IEnumerable<T> without having to modify any existing code but just adding new code to new assembly members.
And they invented extension methods, which would be implemented like static methods and they would act as instance members of a given type.
Since the inception of extension methods, they've been implemented in many other scenarios, but they always cover these two use cases:
I've a large code base and I want to offer a functionality to all types deriving (classes) or implementing (interfaces) some other type without having to modify them implementing a new interface across a lot of code (increasing the chance of introducing new bugs).
I don't own the source code of some project and I want to extend some types to support some new methods.
Anything outside these use cases is an abuse of extension methods.
Extension methods aren't a replacement to regular class-based object-oriented programming.
Basically you could extend every class or interface - nothing else is done with the Linq-extension methods.
However you can not define those methods directly in the interface, you allways need a static public class that contains those extensions.
To answer your questions I doubt that defining a default-behaviour within extension-methods is a good thing as it completely compromizes the actual intention of that interface. When creating an extension-method all instances of that (extented) class/interface share those methods, thus what you´re doing is to say every instance of my interface is able to be treated as my abstract class.
Having said this you should differ between the behaviour (the interface) and the actual processing (the class). Mixing both will eventually make your design quite complicated.
Next is by defining extension-mtehods you completely bypass inheritance. So what if you want to override the default-behaviour? You would be lost defining them as new or any different wewird workaround because your design was not open for inheritance at all.
Last point from my view is that you should use extension-methods for classes you don´t have control about. However when you can modify the code you´ll probably won´t use them.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Somewhere I have read this question. How can we handle situation like this:
I have an interface, In that I have four methods: Add, Subtract, Multiply, Divide.
I have two classes A and B.
I want A and B to implement this Interface. But I want situation like this:
A can access only Add, Subtract.
B can access only Multiply, Divide.
Please tell me how is this possible in C#?
Or by some trick if this is possible please let me know.
The point of an interface is to define a contract between two objects. If you are saying that your object only wants to implement some of the contract, then that breaks the meaning of the interface.
Why don't you use multiple interfaces, one for Add/Subtract and another for Multiply/Divide. Your class can implement any or both of these interfaces.
A class that implements an interface must implement all of its methods. The documentation says:
A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition.
It seems to me that what you need is two interfaces:
IAdditiveOperators which implements addition and subtraction.
IMultiplicativeOperators which implements multiplication and division.
Implementing classes can then implement one or other or both.
Split the interface to two interfaces: one with Add and Substract and name IAddSubstract and another one with Multiply and Divide with name IMultiplyDivide. Then you can add another interface (IOperation) which implements IAddSubstract and IMultiplyDivide
You have two ways to go about it:
Either split up your methods between two separate interfaces and implement one interface containing Add and Subtract in class A and the other one containing Multiply and Divide in class B. That of course means you have two interfaces instead of one, so decide if this is a problem.
OR
If you insist on having only one interface, you can declare A and B as abstract (which of course means you cannot instantiate them)
If going the abstract route, you need to mark interface methods you don't want to implement as abstract as well.
You can't avoid implementing all methods of the interface. If you inherit the interface you have to fulfil it.
In some situations some methods of an interface can't have a useful implementation for a specific class. After you have come to the conclusion that you should implement the interface despite this, there are some things that you can do:
You can implement a method as doing nothing. If the class already does what's expected without it, you can just accept the method call and silently do nothing.
You can throw a NotSupportedException, if some result is expected by calling the method, that the class can't fulfil. Naturally this should only be done if the method is not crucial for how the interface is supposed to be used.
Also, you have the choise of implementing interface members implicitly or explicilty. Implicitly is the normal way, where the member is visible both when the type of the reference is the interface and when it's the class.
To implement a member explicitly makes it only visible when the type of the reference is the interface, not when it's the class.
If the Multiply method is implemented explicitly in the class A (and the interface is named ICanCalc):
A obja = new A();
ICanCalc infa = new A();
infa.Multiply(); // works fine
obja.Multiply(); // gives a compiler error
However, the method is only hidden, you can still use it by simply casting the reference:
(ICanCalc)obja.Multiply(); // works fine
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Original Questions: I know the question sounds pretty "thin", since generic classes (interfaces) and collections go hand in hand. Out of curiosity and a desire to 'cover all the bases' ... are there uses for these generics other than as collections?
The response is that there are too many possibilities to make for a good thread, so let me try to clarify the question because I ( and probably others) will definitely benefit.
My revised question is:
What are applications of instantiated generics (not methods!) in addition to collections? So, now I know there are many ... however, classified by use... what are they?
A concise format for answers is:
Use: Short description or example
(ie) Collections: The generic allows for collections of objects and with a where T: constraint gives access to methods on all members of the collection. (link or reference).
I'm really eager to hear responses.
You can create not only generic types but also generic methods. Though the most common use of generics is for creating collections they are also used for many other purposes such as containers or algorithms.
class Point<T>
{
T x;
T y;
};
class Math<T>
{
T Add(T a, T b);
};
You should also have a look at this discussion: What is cool about generics, why use them?.
I've used generics for a "EventHandler" (with a restriction on the generic that the parameter implemented my BaseEvent class) when sending events via WCF to another piece of the system.
As the comments note, the answer is unequivocally yes. You use generics whenever multiple types (and ideally all types) should have the same behavior (and occasionally state). Collections are an easy example of this, but there are many, many other situations where this holds true and generics are a good choice.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
With dynamic we pretty much have a dynamic pointer, but not exactly a dynamic object. The true dynamic object in C# is the ExpandoObject, but that is a really unknown class for most of people. The expando allows creating and removing members at runtime, much like a hash (similar to JavaScript).
Why the ExpandoObject goodness was implemented in a separate class rather than just being, let's say, implemented as a feature of anonymous types?
Maybe that wouldn't be a good move because the lacking of type-safety? Or maybe due the (DLR) overhead involved?
Because anonymous types have other very important feature - they provide you compile time type safety.
And because dynamic and anonymous types are just different concepts. The first one gives you ability to dispatch object members at runtime, the second lets you create statically typed objects with some base functionality (equality, hashcode, etc) without creating corresponding POCO classes. Why should they be implemented in the same way then?
btw. I use them quite a lot and really rarely needed to use dynamic to deal with them. Are you sure you're using these language features correctly?
Update
I think that's very important part of anonymous types tutorial:
If you must store query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
A question was raised in a discussion I had around whether an interface method should return a Custom object vs a primitive type.
e.g.
public interface IFoo
{
bool SomeMethod();
}
vs
public interface IFoo
{
MyFooObj SomeMethod();
}
Where MyFooObj is:
public class MyFooObj
{
bool SomeProp{get;set;}
}
The argument being that you can easily add properties to the object in the future without needing to change the interface contract.
I am unsure what the standard guidelines on this are?
IMHO Changing the MyFooObj is the same as changing/adding methods to the IFoo Interface - so no I don't think it's a good idea add just another abstraction - remember YAGNI
My standard response is - YAGNI.
You can always change things if it turns out that way, in particular if you control the full source of the application and how the interface is used.
Wrapping a boolean just in order to forecast the future is only adding complication and additional layers of abstraction when they are not currently needed.
If you are using DDD and specific modelling techniques in your codebase, is can make sense to have such aliases to booleans, if they are meaningful in your domain (but I can't see this being the case for a single boolean value).
I don't see the point of encapsulating primitive types in a custom object.
If you change the definition of this custom object, then you actually change the contract because the function doesn't return the same thing.
I think it's again an over-engineered "pattern".
There are no general guidelines regarding this.
As you pointed out, if you have semantics around the return type that you think strongly believe may change or may need to be updated in the future it may be better to return the complex type.
But the reality is that in most circumstances it is better to keep things simple and return the primitive type.
That depends somewhat on what you like. My opinion, that in your sample case, I would stick with the simple bool in the interface definition for those reasons:
it is the simplest to read possibility
no one looks for methods that aren't available
IMHO, an object makes sense only when a certain amount of complexity/grouping is required as a result.
If its not required to begin with you should not wrap it changing what is returned inside the object is simply the same as changing the interface which breaks rule number one of programming with interfaces.
Its right up there with designing for extension, YAGNI (you ain't gonna need it).
As a side note I got told off for stuff like this early in my career.
If you ever need to return something more than a boolean, it is extremely likely that you are going to modify other parts of the interface as well. Do not make things more complex than they need to be: simplicity is prerequisite of reliability.
In addition to the other answers, adding a new field to a custom class is technically still a potential breaking change to the interface's consumers. Link
Just thought I'd mention that if MyFooObj is in an assembly which is strong named, you update it, its version gets updated - old clients will immediately break (e.g. InvalidCastException) due to a version mismatch (it won't attempt a partial bind due to strong nameness) unless they recompile with the new version. You've still changed the interface contract. So best to keep things simple, return the primative type and declare your change of contract more explicitly.