Currently, I am learning ASP.NET MVC 5. I am stuck at one point in the book called Dependency injection. I will try my best to learn how to use it, but before I do that I would like you to help me. I started learning C# a few weeks ago and the one thing I haven't figured out yet is the interface. I know why and when to create it, but I don't really understand when it comes to making reference variables.
Let's say I have an interface called IValueCalculator. Then I have a class LINQValueCalculator which implements IValueCalculator. Now, here comes my misunderstanding.
LINQValueCalculator referenceVariable = new LINQValueCalculator();
This will create a new instance and will be bound to use with referenceVariable.
I can then use everything that interface told me to use and any added stuff to the class.
But, what if I do this...
IValueCalculator referenceVariable = new LINQValueCalculator();
What is the difference? Can I still do the same thing as before or has something changed?
What if I had something like this
public class ShoppingCart
{
private IValueCalculator calc;
public ShoppingCart(IValueCalculator calcParam)
{
calc = calcParam;
}
This means I can put only those object's references which implement that interface right? Or am I wrong?
When I truly understand the point under all this, I will then continue learning Ninject (DI).
The underlying object is still a LINQValueCalculator but you can only refer to the IValueCalculator methods and properties while using referenceVariable because that variable is just the interface.
To make use of any of the properties of LINQValueCalculator you'll have to cast the variable. You can do this each time you need to use it:
((LINQValueCalculator)referenceVariable).SomeMethod();
or just the once:
var anotherReference = (LINQValueCalculator)referenceVariable;
Here, anotherReference and referenceVariable are references to the same object so changes to one will be reflected in the other.
Using the interface means that you can pass the object to other code that doesn't know (or need to know) about LINQValueCalculator, but acts on the properties and methods of IValueCalculator.
What is the difference? Can I still do the same thing as before or has something changed?
You can do the same things :-)
Unless if the concrete type offer more method than the interface !
This means I can put only those object's references which implement that interface right? Or am I wrong?
And you're right !
The benefits of using interface in the last case is that you can receive an object that implements IValueCalculator but you (really) don't care about the concrete type.
If you decide to create a second concrete type that implements the IValueCalculator (more performant maybe ?), you can do it and inject it into ShoppingCart constructor without change the ShoppingCart code !
I'm rewriting a desktop solution and I have the main root Form, that contains Properties that should be accessible by other elements of the application.
You could use an Interface method to get the property or your could get the Form as a dynamic object and query the property. Code example below.
Interface-based approach
public interface IUersInterfaceMainScreenGet
{
dynamic GetClientDetails();
}
The forms interface-implementation looks like this:
public dynamic GetClientDetails()
{
return currentClients;
}
Calling the Interface
var mainScreen = (InterfaceProject.IUersInterfaceMainScreenGet)System.Windows.Forms.Application.OpenForms["mainScreenForm"];
return mainScreen.GetLastBodyPluginFormName();
Dynamic-based appraoch
dynamic form = Application.OpenForms["MainScreenForm"];
form.currentClients
Both instance needs to get the current Active form, but Which once would be the best in practice to memory usage?
With the Interface the Property that I want to get can be private, but for Dynamic it needs to be public
Your question is quite hard to understand. However I have a guess on what you mean.
When you have your interface you can get the clients details via a method called GetClientDetails. On the form its implementation simply returns the private field (not property) currentClients.
Usually it´s a good idea to know the types you handle with, so using interfaces is a good idea as you have compile-time checks on what you can access and what not. In your case you kno that the object returned from Forms.Application.OpenForms["mainScreenForm"] has a method for accessing the client-details. When using only dynamic you have no knowledge at all on the contained object, you could do everything with it - whereas the most will fail at runtime. But why do you want to throw away knowledge that you already have?
So my basic suggestion is: allways use strongly-typed interfaces. Only in a few seldom circumstances you may actually need dynamic.
Concerning the memory-footprint there is no difference between both solutions. What counts is the memory of your actual instance, which is the same, no matter on how you access the data. So you need a field in both cases. The only difference is how you access that field, one time you this happens directly (dynamic) and on the interface you access it by calling the method.
So there is no difference on the following two statements concerning memory-footprint:
var form = (IUersInterfaceMainScreenGet)Application.OpenForms["mainScreenForm"];
return form.GetClientDetails();
And
dynamic form = Application.OpenForms["MainScreenForm"];
return form.currentClients
Simple factory using reflection involves storing (registering) various type names with their corresponding class type in a hash table, then using this hash table for generating objects in the factory.
interface Product
{
void foo();
}
class ProductFactory
{
HashTable m_RegisteredProducts = new HashTable();
public void registerProduct(string productID, Type p) {
m_RegisteredProducts.add(productID, p);
}
public Product createProduct(string productID){
return (Product) new m_RegisteredProducts[productID];
}
}
I'm not clear on when does the process of registering a new type happen since all types to be used are to be loaded into the hash table at runtime. Where is the call to registerProduct() to be made?
Calling registerProduct() for all different classes at a single place inside ProductFactory class doesn't make sense since it would defeat the purpose of using reflection over naive switch/case method.
If registerProduct() is called inside the class definition of all classes implementing the interface, then an instance of the class is created after/using the Factory hence will always give an error.
Your code doesn't do reflection as it's expecting an instance implementing the Product interface, not a type. You would need addProduct to take a Type instance, check if it implements the Product interface, then dynamically create instances of it in createProduct (using something like type.GetConstructor(<constructor signature>).Invoke(<arguments>);)
Here's an article I wrote a long time ago on something similar: http://blixt.org/2009/06/05/getting-types-implementing-class-or-interface
Calling registerProduct() for all different classes at a single place inside ProductFactory class doesn't make sense since it would defeat the purpose of using reflection over naive switch/case method.
Reflection is useful when extended product classes are added into a location (say a plug-ins directory). You have a list of strings to identify the supported plug-ins that can either be defined in a text file (application properties, which provides an added layer of security) or by (via reflection) scanning said plug-ins directory (less secure if someone can drop a hacked product in there). Disclaimer: I've never done this in C#, but it works well in Java. Apart from new product code and eventually modifying the properties file, there is no modification to the application code.
If registerProduct() is called inside the class definition of all classes implementing the interface, then an instance [of] the class is created after/using the Factory hence will always give an error.
I'm not sure that's always the strategy of the code in your question (where is it from?). You might want to read more about the different strategies of reflection combined with simple factory at http://www.codeproject.com/Articles/37547/Exploring-Factory-Pattern
It depends. There are different scenarios that call for different strategies.
One strategy that I saw quite often if all product types are defined in the same assembly (or a list of assemblies) you could call something like this:
var productTypes= from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetInterfaces().Contains(typeof(IProduct));
and then call registerProduct() for every element in productTypes.
I created a class called MostRecentStack<T> which is a stack that only keeps a certain number of items, dropping the ones at the bottom to make room for new ones. I'd like to have a variable that can store a reference to either a regular ("infinite") stack, or one of my custom type, depending on the circumstances, but C# defines no generic "stack" interface. Normally this wouldn't be a problem, but I'd like System.Collections.Generic.Stack<T> to implement the interface as well.
As long as a class provides the required members, is there any way to, in the interface definition, tell the compiler to consider a class as implementing the interface? I'd like to be able to do this without having to use as or other methods of typecasting.
The exact thing you're asking for isn't possible. However, something like should be very similar to what you want:
public class CompatibleStack<T> : System.Collections.Generic.Stack<T>, IYourStackInterface<T>
{
}
The CompatibleStack is functionally equivalent to System.Collections.Generic.Stack, except it now implements IYourStackInterface.
As long as System.Collections.Generic.Stack has all the right members to implement IYourStackInterface, this should compile fine. And you can pass a CompatibleStack around as an IYourStackInterface without any problems.
No, it is not possible to add new interface to existing class that you don't own. Options:
if you get instance of the class via some dependency injection controller you may be able to wrap class with proxy that will implement interface by calling matching methods.
you can simply derive from existing class and add interface (if it is not sealed) and start using your class.
in your particular case as Baldrick pointed out you can do reverse - derive from existing class and implement interface.
you can try to use dynamic to get some duck typing (as both classes will have matching methods) for some performance, readability and strong type cost.
Side note: in general C# does not support duck typing, but there is one case (foreach) where implementing interface is not strictly required - just having correct methods on collection is enough to support foreach.
Either in C# or Java or in any other language which follows oops concepts generally has 'Object' as super class for it by default. Why do we need to have Object as base class for all the classes we create?
When multiple inheritance is not possible in a language such as C# or Java how can we derive our class from another class when it is already derived from Object class. This question may look like silly but wanted to know some experts opinions on it.
Having a single-rooted type hierarchy can be handy in various ways. In particular, before generics came along, it was the only way that something like ArrayList would work. With generics, there's significantly less advantage to it - although it could still be useful in some situations, I suspect. EDIT: As an example, LINQ to XML's construction model is very "loose" in terms of being specified via object... but it works really well.
As for deriving from different classes - you derive directly from one class, but that will in turn derive indirectly from another one, and so on up to Object.
Note that the things which "all objects have in common" such as hash code, equality and monitors count as another design decision which I would question the wisdom of. Without a single rooted hierarchy these design decisions possibly wouldn't have been made the same way ;)
The fact that every class inherits object ensured by the compiler.
Meaning that is you write:
class A {}
It will compile like:
class A : Object{}
But if you state:
class B : A {}
Object will be in the hierarchy of B but not directly - so there is still no multiple inheritance.
In short
1) The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class.
2) You can have B extend C, and A extend B. A is the child class of B, and B is the child class of C. Naturally, A is also a child class of C.
Well, the multiple inheritance of Object does not apply - you can think of it as:
"If a type doesn't have a base type, then implicitly inject Object".
Thus, applying the rule ad-nauseam, all types inherit from object once and once only - since at the bottom of the hierarchy must be a type that has no base; and therefore which will implicitly inherit from Object.
As for why these languages/frameworks have this as a feature, I have a few reasons:
1) The clue's in the name 'Object Oriented'. Everything is an object, therefore everything should have 'Object' (or equivalent) at it's core otherwise the design principle would be broken from the get-go.
2) Allows the framework to provide hooks for common operations that all types should/might need to support. Such as hash-code generation, string output for debugging etc etc.
3) It means that you can avoid resorting to nasty type casts that can break stuff - like (((int *)(void*))value) - since you have a nice friendly supertype for everything
There's probably loads more than this - and in the time it's taken me to write this 6 new answers have been posted; so I'll leave it there and hope that better people than I can explain in more detail and perhaps better :)
Regarding the first part of your question, it's how classes receive common properties and methods. It's also how we can have strongly-typed parameters to functions that can accept any object.
Regarding your second question, you simply derive your class from the other class; it will then be a descendant of that class, which is in turn a descendant of Object. There's no conflict.
You have the Object base class because amongst others because the Object class has methods (like, in .NET, GetHashCode(), which contain common functionality every object should have).
Multiple inheritance is indeed not possible, but it is possible to derive class A from class B, because A may not directly derive from Object, but B does, so all classes ultimately derive from Object, if you go far enough in the class' inheritance hierarchy.
Just to compare, let's take a look at a language that doesn't enforce a single root class - Objective-C. In most Objective-C environments there will be three root classes available (Object, NSObject and NSProxy), and you can write your own root class by just not declaring a superclass. In fact Object is deprecated and only exists for legacy reasons, but it's informative to include it in this discussion. The language is duck typed, so you can declare a variable's type as "any old object" (written as id), then it doesn't even matter what root class it has.
OK, so we've got all of these base classes. In fact, even for the compiler and runtime libraries to be able to get anywhere they need some common behaviour: the root classes must all have a pointer ivar called isa that references a class definition structure. Without that pointer, the compiler doesn't know how to create an object structure, and the runtime library won't know how to find out what class an object is, what its instance variables are, what messages it responds to and so forth.
So even though Objective-C claims to have multiple root classes, in fact there's some behaviour that all objects must implement. So in all but name, there's really a common primitive superclass, albeit one with less API than java.lang.Object.
N.B. as it happens both NSObject and NSProxy do provide a rich API similar to java.lang.Object, via a protocol (like a Java interface). Most API that claims to deal with the id type (remember, that's the "any old object" type) will actually assume it responds to messages in the protocol. By the time you actually need to use an object, rather than just create it with a compiler, it turns out to be useful to fold all of this common behaviour like equality, hashing, string descriptions etc. into the root class.
Well multiple inheritance is a totally different ball game.
An example of multiple inheritance:-
class Root
{
public abstract void Test();
}
class leftChild : Root
{
public override void Test()
{
}
}
class rightChild : Root
{
public override void Test()
{
}
}
class leafChild : rightChild, leftChild
{
}
The problem here being leafChild inherits Test of rightChild and leftChild. So a case of conflicting methods. This is called a diamond problem.
But when you use the object as super class the hierarchy goes like this:-
class Object
{
public abstract void hashcode();
//other methods
}
class leftChild : Object
{
public override void hashcode()
{
}
}
class rightChild : Object
{
public override void hashcode()
{
}
}
So here we derive both classes from Object but that's the end of it.
It acts like a template for all the objects which will derive from it, so that some common functionality required by every object is provided by default. For example cloning, hashcode and object locking etc.