semantically represent generics - c#

I am trying to understand generics in a semantic way. For instance, abstract classes seemed to snap into place for me when I read people refer to them as structures that can set policy. Interfaces snapped when I read people refer to them as collaboration contracts.
What are some good ways to think about generics that might help me to differentiate them from other OO structures and write more intelligent APIs?

Think of generic classes as stencils to make other classes (similarly, generic functions are stencils for making other functions). Type parameters serve as openings in your stencils: by plugging in a concrete type into them, you make the generic class or the generic function into a real class or function. The type parameters "stick through" the designated holes in the stencil, producing a complete definition.

It seems you want to approach your understanding from a top-down perspective. "What is it" in a qualitative sense and then derive the real meaning from there. Isn't it easier to simply learn what these different constructs do rather than trying to come up with labels? i.e. approach it from a bottom-up perspective and infer your own qualitative descriptions from what you've now already understood firsthand.
Abstract classes require you to implement a property or method and can't be instantiated. What distinguishes it from an interface? It requires subclasses to choose yours as its only base class. Interfaces face no such restriction but require you to define its entire behavior in the implementation, rather than relying on some of the behavior to be defined in the base class.
Similarly, generics allow you to introduce types as variables that can be specified by the caller. The utility of this is analogous to method parameters in general, just taken to a higher level. In other words, method parameters allow you to vary the implementation based on some input specified by the caller. Generic parameters allow you to vary the implementation based on some (other) input (i.e. types) specified by the caller.
Surely it's clear why List<T> is more useful than ArrayList. I'm not really sure why metaphors are really helpful for understanding why.

You could view them as wrappers around object types. You are creating functions that will do something for whatever type of object it is instantiated for, so it's like a template that will perform the same work for multiple types of objects.
Microsoft's introduction to generics might have some good descriptions as well
http://msdn.microsoft.com/en-us/library/ms379564(v=vs.80).aspx

Related

Interfaces or classes when using objects

In my project I have defined an interface to describe the methods that each of my different database connection classes must have. This is called IDatabaseConnectivityObject. Each of my classes implements this interface to make sure that they all contain the same methods for running queries, making connections etc etc.
Consider the following code:
IDatabaseConnectivityObject adoDataBaseConnection = new DbProviderFactoryConnection();
DbProviderFactoryConnection adoDataBaseConnection = new DbProviderFactoryConnection();
Will the above lines both behave the same? If so why? If not then why not? What are the benefits of both?
It may be a really stupid question but I havent used interfaces all that long and I am not sure what line 1 does. It was my understanding that you couldnt make an instance of an interface as it merely defines behaviour so how is that line possible?
Will the above lines both behave the same? If so why?
At runtime yes. The difference is that if you declare the variable of type IDatabaseConnectivityObject then at compile time you will be able to see only the members of this interface on the variable. If on the other hand you declare it as DbProviderFactoryConnection then you will see all the members of this class.
As a good practice it is recommended to always work with the highest possible type in the hierarchy when declaring the variable (IDatabaseConnectivityObject in this case) which allows you to access all members that the consumer will need.
The first would allow you to swap in a different implementation of you IDatabaseConnectivityObject moving forward.
This is a good practice as it allows your system to be more resistant to change moving forward. Keeping the cost of change low is key.
Interfaces define the contract that consumers can rely on, the API if you will. The two lines are functionally the same if you intend to use members that are present on the interface.
Using the interface just expresses that you don't care how something is implemented, just that it is implemented to contract. Interfaces also promote Loose Coupling.
The benefit of programming against an interface is that you are programming against the "agreement" and not the "execution", or the contract and not the implementation. This has a large positive impact on testing as you can mock or stub interfaces during tests to reduce the number of extraneous dependencies in a test scenario.
A similar benefit to above is that using interfaces along with something like the factory pattern, IoC, or DI you can provide different implementations of the interface on the fly - for example, a different business logic handler for a different customer.
Another benefit is that it helps get around the lack of multiple inheritance. Most things can be expressed nicely via interfaces, and classes can implement multiple interfaces.
You've asked for benefits.
When you are programming against interfaces (and are using factories to create the concrete types) this makes unit-testing easier as you can mock the instance that is put into the logic (unit).
This is actually a 'Design Pattern Principle':
"Program to an 'interface', not an 'implementation'." (Gang of Four 1995:18)

How to utilize C# attributes and reflection to inject/force late bindings on marked objects?

I love design patterns, the problem is that some can be really tedious to implement.
For example, decorating an object that has 20+ members is just plain annoying.
So, I wanted to create a nice library of design patterns to be applied to classes (either as base classes or attributes) to make implementation of these patterns much quicker and eaiser.
The problem is...I'm not quite sure where to start - because I am mostly unfamiliar with attributes and reflection.
I would like to utilize attributes to mark Singletons (similar to the Export tag), Multitons, and Decorators...if at all possible. But I don't even know where to start in order to create a singleton attribute that alters the functionality of its instances.
My limited research has led me to believe that using reflection/late binding through an attribute and gaining access to all marked classes in the assembly, would allow you to hack together a singleton...but I'm still not entirely sure how that would be done.
A framework I found, called Ninject 1.0, created a Singleton attribute - but the library is so extensive and undocumented, that I am currently unable to follow its logic.
I feel like a library with this sort of functionality would be a great contribution to many developers out there. So, it would be greatly appreciated if someone could provide some sample code that gets me pointed in the right direction to create one of these patterns as an attribute - whose code isn't overly involved. Or if someone would be willing to walk me through Ninject's singleton attribute implementation so I may work off of that...
Thank you for your time and consideration.
I think you have a slight confusion on what design patterns mean.
A pattern is really a common way of doing things, designed to solve a particular problem.
You don't really use patterns for patterns' sake. More patterns usage doesn't automatically means good. You use a pattern to solve a type problem -- and hopefully that pattern is the recognized best-practice way to solve that problem. Don't try to appy a pattern to your code because you can.
Now, after all this, it can really be seen that what you are planning to do is not the right way of going about implementing pattern(s). You don't mark code with attributes etc. and then call them patterns. The pattern is your code. Your code is the pattern. For example, you don't mark a publisher/subscriber pattern on a class unless it really implements publish/subscribe functionalities. For example, you don't mark a class with "Singleton" and then it becomes a singleton pattern; using the Singleton pattern requires you to code your program (and your classes) around that design.
You may, however, mark code or classes with certain attributes that can aid in checking whether the code/classes conform to a particular pattern.
For example, you may implement a type checker that goes through all your class, check if anything is marked "publisher" and see if that class implements the "IPublisher" interface. Or your type checker can check if any class is marked "Singleton" whether the constructor allows construction of more than one instance at any one time.
But attributes and reflection is typically not the tools to implement a pattern.
In C#, where there is no multiple inheritance, the way you implement patterns is sometimes through the base class only. For example, you may implement a "singleton" pattern by declaring a "SingletonObject" base class which limits itself to only one instantiation. Then you derive any class that you want to be singletons from this base class. For example, you may implement a "publish/subscribe" pattern by declaring IPublisher and ISubscriber interfaces.
Now, if you really just want to just use the Decorator pattern on C# classes (as per the title of your question), what you are looking for is an automatic wrapper object generator. You can based your wrapper on an ExpandoObject, loop through the properties of the base object, and add properties to the ExpandoObject that simply delegates back to the base object. Then add new properties to the ExpandoObject on top of your base object. Voila! You get your auto-Decorator-Pattern wrapper class generator.

fields not allowed in C# interface

There are quite a lot of deviations in Java and C# languages, one of which I observed was we cannot add variable constants in an interface. Being from Java background I got baffled to see compilation error when I tried this.
Does anyone has explanation why it is so?
A field is an implementation detail of a class and should not be exposed an its interface.
An interface is a way to abstract away implementation details of a class. These two concepts look contradictory and don't really fit together.
You can declare properties in interfaces instead.
UPDATE (after realizing the question was about constants, not variable fields): I think (purely my personal speculation) that Java decided to allow such a construct because it didn't have enum types back then. C# has had enums since the beginning and preferred those to constants most of the time. Moreover, you can create a static class in C# and add everything you like in it and ship it along the interface without any real hassles. Supporting such a construct would just make interface definitions more complicated.
I've rarely wanted to have an actual constant in an interface - they usually make more sense in classes. The practice of using a Java interface to just contain constants (in order to reduce typing in classes that use them) is nasty; I'd only put constants in interfaces where they were related to functionality within the interface itself.
However, on occasion I've thought it would be nice to be able to define an enum within an interface, if that's the only context in which the enum is anticipated to be used. Interestingly, VB allows this even though C# doesn't.
Effectively both of these would be a way of turning the interface into a "mini-namespace" in its own right. However, I can't say I've missed it very often when writing C#. As the C# team is fond of saying, features aren't removed - they're added, and the cost of adding a feature is very high. That means the feature really needs to pull its weight - there has to be a significant benefit before the feature is added. I personally wouldn't put this very high up on the list.
Related thought: it might be nice to be able to define a nested class within the interface, usually an implementation of the interface - either to express its contracts or to act as a "default" implementation for situations where there is such a thing.
and adding constants to interfaces is discouraged in Java too (according to Effective Java at least)
Adding constants to an interface is wrong and should almost never be done. In the past many people declared Interfaces with many constants and then made another class implement this interface so they could make use of the constants without qualifying said constant. This is of course another anti pattern and was only done because people were lazy. If you really want a constant in an interface define a method that returns that constant.

Benefits of implementing an interface

what are the benefits of implementing an interface in C# 3.5 ?
You'll be able to pass your object to a method (or satisfy a type constraint) that expects the interface as an argument. C# does not support "duck typing." Just by writing the methods defined by the interface, the object will not automatically be "compatible" with the interface type:
public void PrintCollection<T>(IEnumerable<T> collection) {
foreach (var x in collection)
Console.WriteLine(x);
}
If List<T> did not implement the IEnumerable<T> interface, you wouldn't be able to pass it as an argument to PrintCollection method (even if it had a GetEnumerator method).
Basically, an interface declares a contract. Implementing an interface enforces your class to be bound to the contract (by providing the appropriate members). Consequently, everything that relies on that contract (a method that relies on the functionality specified by the interface to be provided by your object) can work with your object too.
The main benefit is about code readability, code maintainability and code "semantics".
Code readability: An interface constitutes a declaration about intentions. It defines a capability of your class, what your class is capable of doing. If you implement ISortable you're clearly stating that your class can be sorted, same for IRenderable or IConvertible.
Code semantics: By providing interfaces and implementing them you're actively separating concepts in a similar way HTML and CSS does. A class is a concrete implementation of an "object class" some way of representing the reality by modeling general properties of real life objects or concepts. An interface define a behavioral model, a definition of what an object can do. Separating those concepts keeps the semantics of your code more clear. That way some methods may need an instance of an animal class while other may accept whatever object you throw at them as long as it supports "walking".
Code maintainability: Interfaces helps to reduce coupling and therefore allow you to easily interchange implementations for the same concept without the underlying code being affected. You can change the implementation of a IMessage easily by defining a new class that implements the interface. Compare that to sistematically replacing all references from CMessage to CMyNewMessageClass.
It will help when you try to:
Unit test with Stubs / Mocks
Implement Dependency injection
Solve world hunger (although this unproven!)
Kindness,
Dan
Interfaces provide no actual advantage. Anything that can be done with an interface can, and should be done using other language constructions. Multiple inheritance is oft quoted as the only REAL benefit derived from using interfaces, but I can do multiple inheritance quite easily and clearly in C# - I do it every day. Changing the code without "breaking" the interface is the silliest of all excuses... That applies the same to concrete classes as it does to abstract classes or interfaces. As long as the functional signature does not change, you haven't broken the interface. Doesn't matter where it was declared. Simply putting a functional prototype in a separate file and naming it with an "I" in front buys nothing - except that you end up with twice as many source files to maintain. The supposition that the interface is defined early, and then maintains the contract is ridiculous. Interface methods and their parameters change ALL the time, because everything is never known up-front. That's why MicroSof stopped using them long ago. They had IUnKnown, IUnknown2, etc. It created a mess.
The main benefits of interfaces is mostly related to project design.
If you use an interface:
The consumer of the interface should implement that interface.
Designing bridge patters.
Creating a contract so that user must adhere the rules of the interface.
Can take only interface part (Object) from the main class.
Even class is private, can obtain the interface object from that
Multiple inheritance kind of style.
Need not be should implement, simple go for if implements that means if you want you can implement other wise can drop it..
Cleaner code.
Implementation which changes depends on class can go ahead with interface.
If each class have separate implementation of a method better to go for interfaces. For example IEnumerable in collections.
According to C# Architect, in a simple word it's a contract. Consumer must adhere to it.
An interface defines a contract (things that an object is able to do), while a concrete class (or struct) defines the concrete behavior.
For an example, IList is an interface, it defines the methods that a concrete object has to provide in order to be used like any other object implementing IList. Everywhere an IList can be used, your object that implements IList can be used as well. The way you concretely implement it and the way your object behaves when those IList methods are called is left to you.
If you work in a huge, commercial software house - you MIGHT want to consider the judicial use of Interfaces. Otherwise, you should stay away from them. Same for multi-threading. If I see one more script-kiddie app that spawns 20 threads to write "Hello World" I'm gonna freak. Multi-threading should be completely reserved for apps that require it, usually in a multi-processing environment. 90% of the time it causes more harm than good. And don't bother with the thread highjack / off-topic comments. I don't care. I've been doing this longer than most of you have been alive. Rank has its privileges.
You aren't tied to class inheritance - you can apply an interface to any class. Any class can have multiple interfaces - C# doesn't support multiple class inheritance, i.e. you are providing a good abstraction layer through the interface
An Interface is a reference type and it contains only abstract members. Interface's members can be Events, Methods, Properties and Indexers. But the interface contains only declaration for its members. Any implementation must be placed in class that realizes them. The interface can't contain constants, data fields, constructors, destructors and static members. All the member declarations inside interface are implicitly public.
The way I understand it interfaces are most useful in these cases:
Cleaner division of labor among programmers. Lead programmer writes interface and junior programmer writes its implementation. That makes perfect sense to me. Lead programmer could write pseudocode instead of interface though.
Some specific situation, where you need 2 or more different implementations of the same class, for example interface animal and classes tiger and lion that use it. And even here it doesn't makes much sense, because lions and tigers share some things in common. Abstract class would be better, because if you use interface you have to write common functions in separate classes which leads to code duplication, which is bad.
You write a library and want it to be modifiable by users. So you write interface and its class implementation. User of your lib still has the possibility to write his own implementation class, which may use different technology/algorithm which achieves the same result, but maybe in a faster way for example. This is also the reason why we meet so many interfaces in libs we use, but rarely feel the need to write our own interfaces. Because we don't write libraries.

C#-Generics -ISerializable,IEnumerable,IList -efficient application

I need simple example to use ISerializable,IEnumerable,IList with Generics efficiently.
Also wish to know what are all the other Interfaces we can use along with Generics.
Update :
The task i need to perform is using these interfaces
I have to serialize the custom Types
Collect them in Generic object
Iterate them to find the match
This question is very broad.
Note that the interfaces you've listed are not all about the same thing.
ISerializable is not generic, and deals with serialization of objects to streams or similar.
IEnumerable is about being able to enumerating over a collection or something that produces a stream of elements.
IList is an interface that is typically implemented by such a collection.
It would help us helping you if you could narrow down your question somewhat. As your question stands now, it's more like "I need to know everything there is to know about cars".
As for "all other interfaces that can be used with generics", have you looked at the MSDN Documentation for the .NET framework classes?
I have a feeling that this question is a homework question...but I'll bite with a little information.
Generics != Interfaces. Basically you can use any interface that you want with Generics, it is one of the more powerful parts of generics, by using interfaces that you create, you can then define generic methods that process multiple concrete implementations by limiting the generic type to objects that implement a specific interface.

Categories

Resources