Reference specific class from its generic base class - c#

When working with generics if I have for example a class:
class Foo<T> where T:Cheese
{
}
and then 2 derived classes
class FooDerivedBlue:Foo<BlueCheese>
{
}
class FooDerivedWhite:Foo<WhiteCheese>
{
}
where BlueChesse and WhiteCheese inherit from chesse.
Now there is another class, that will conditionally use FooDerivedBlue or FooDerivedWhite.
The class should have a property like
public Foo<Cheese> Foo {get;set;}
so I can set it to the FooDerivedXXX I need at runtime.
When doing this an trying to set Foo=new FooDerivedWhite() the compiler will complain, since FooDerivedWhite cant be converted to Foo<cheese>.
A more practical example:
If I have a
ArticleRepository<T>
AssemblyArticleRepository:ArticleRepository<AssemblyArticle>
ProductionArticleRepository:ArticleRepository<ProductionArticle>.
ProductionArticle and AssemblyArticle inherit from Article.
Both specific repositories inherit from ArticleRepository and have a lot of common logic. There are certain parts I need only access to the logic they shared (for example adding a new item or deleting it) and in order to avoid duplicate code, I want to instantiate the proper repo and pass it.
For example, I could have an ArticleService, which I pass a type and it instantiates the right repository. Instead, I would need to have a service for each Article type. (??- with my actual knowledge)
Which is the way to solve it in .NET? Or maybe I am facing the problem/writing my code in a wrong way?
Update Here a gist with the concrete problem:
https://gist.github.com/rgomez90/17ec21a1a371be6d78a53a4072938f7f

There are a few ways to deal with this, but the most straightforward is probably to make your "other class" also have a generic type parameter that describes what kind of cheese it operates on. Then all the types can be statically correct.
public abstract class Cheese { }
public class BlueCheese : Cheese { }
public abstract class CheeseTool<T> where T:Cheese { }
public class BlueCheeseTool : CheeseTool<BlueCheese> { }
public class CheeseEater<T> where T : Cheese {
public T Cheese;
public CheeseTool<T> Tool;
}
Then all typing is statically correct:
CheeseEater<BlueCheese> eater = new CheeseEater<BlueCheese>();
eater.Cheese = new BlueCheese();
eater.Tool = new BlueCheeseTool();
More complicated solutions might involve explicit casts and type factories, but simplest is best if it does the job.

Related

Is there a programming pattern to provide overrideable defaults for a generic class in C#?

Suppose that I have a class BaseClass that has two child classes ChildClassA : BaseClass and ChildClassB : BaseClass. For each child class, I want to provide some implementation for two per-class constants, Zero and One, so that the following code would work:
var valueOfZeroA = ChildClassA.Zero;
var valueOfOneB = ChildClassB.Zero;
I should also be able to create a generic class that has a method that selects the appropriate value based on the generic type.
class GenericUsingClass<T> where T : BaseClass
{
public void DoStuff()
{
var valueOfZero = T.Zero;
var valueOfOne = T.One;
}
}
For instance, if I created a new GenericUsingClass<ChildClassA>(), then, the value of valueOfZero would be the same as ChildClassA.Zero.
Here is my problem: I need some programming pattern to implement something like this. I know that the syntax in my code examples will not be possible in the solution; it is just for illustrative purposes. I have provided a possible solution but I find it kind of ugly and am wondering if anyone can provide me with a better solution or explain why mine might be as good as it gets.
So far, I have come up with a factory pattern that seems like it would work decently. It goes as follows:
For each child class of BaseClass, there needs to be a factory class such as ChildClassAFactory and ChildClassBFactory each deriving from a class BaseClassFactory.
Then, BaseClassFactory would be defined as:
abstract class BaseClassFactory<T> where T : BaseClass
{
public abstract T Zero() { ... }
public abstract T One() { ... }
}
and the child factories would implement the methods Zero() and One().
The GenericUsingClass would have to then be refactored into:
class GenericUsingClass<T> where T : BaseClass
{
public void DoStuff()
{
BaseClassFactory<T> factory = new BaseClassFactory<T>();
var valueOfZero = factory.Zero();
var valueOfOne = factory.One();
}
}
or alternatively, using dependency injection:
class GenericUsingClass<T> where T : BaseClass
{
public void DoStuff(BaseClassFactory<T> factory)
{
var valueOfZero = factory.Zero();
var valueOfOne = factory.One();
}
}
I dislike this approach because
It requires twice as many classes to implement the functionality of a single child class although this is my lesser concern.
I have to either create or inject an object factory in my generic using class which seems to add clutter to the code and make the implementation less easy to use.
I also know that reflection would be a possibility but it seems like overkill for this problem and would greatly messy things up. I'm just wondering what the best software architecture idea would be.
Thanks!

Accepting multiple similar entities in a Method - Elegant solution

I have two data entities, which are almost similar, design is something like:
public Class Entity1 : Base
{
public int layerId;
public List<int> Groups;
}
Difference is Entity1 has an extra collection of integer Groups
public Class Entity2 : Base
{
public int layerId;
}
These entities are filled as an input from UI using Json, I need to pass them to a processing method, which gives the same Output entity. Method has a logic to handle if List<int> Groups is null, I need to create a method which is capable of handling each of the input in an elegant manner. I cannot just use only Entity1, since they are two different functional inputs for different business process, so using Entity1 as direct replacement would be a mis-representation
Instead of creating overload of the function, I can think of following options:
Use object type as input and typecast in the function internally
I think we can similarly use dynamic types, but solution will be similar as above, it will not be a clean solution in either case, along with the switch-case mess.
What I am currently doing is processing method is like this:
public OuputEntity ProcessMethod(Entity 1)
{
// Data Processing
}
I have created a constructor of Entity1, that takes Entity2 as Input.
Any suggestion to create an elegant solution, which can have multiple such entities. May be using generic, where we use a Func delegate to create a common type out of two or more entities, which is almost similar to what I have currently done. Something like:
Func<T,Entity1>
Thus use Entity1 output for further processing in the logic.
I need to create a method which is capable of handling each of the input in an elegant manner
Create an Interface, or a contract so to speak, where each entity adheres to the particular design. That way common functionality can be processed in a similar manner. Subsequently each difference is expressed in other interfaces and testing for that interface sis done and the differences handled as such.
May be using generic,
Generic types can be tested against interfaces and a clean method of operations hence follows suit.
For example say we have two entities that both have Name properties as string, but one has an Order property. So we define the common interface
public interface IName
{
string Name { get; set; }
string FullName { get; }
}
public interface IOrder
{
decimal Amount { get; set; }
}
So once we have our two entities of EntityName and EntityOrder we can add the interfaces to them, usually using the Partial class definition such as when EF creates them on the fly:
public partial class EntityName : IName
{
// Nothing to do EntityName already defines public string Name { get; set; }
public string FullName { get { return "Person: " + Name; }}
}
public partial class EntityOrder : IName, IOrder
{
// Nothing to do Entity Order already defines public string Name { get; set; }
// and Amount.
public string FullName { get { return "Order: " + Name; } }
}
Then we can process each of them together in the same method
public void Process(IName entity)
{
LogOperation( entity.FullName );
// If we have an order process it uniquely
var order = entity as IOrder;
if (order != null)
{
LogOperation( "Order: " + order.Amount.ToString() );
}
}
Generic methods can enforce an interface(s) such as:
public void Process<T>(T entity) where T : IName
{
// Same as before but we are ensured that only elements of IName
// are used as enforced by the compiler.
}
Just create generic method that will do this work for you:
List<OuputEntity> MyMethod<T>(T value) where T : Base
// adding this constraint ensures that T is of type that is derived from Base type
{
List<OutputEntity> result = new List<OutputEntity>();
// some processing logic here like ...
return result;
}
var resultForEntity1 = MyMethod<Entity1>();
var resultForEntity2 = MyMethod<Entity2>();
P.S. check my answer for this question as you may find it useful too:
map string to entity for using with generic method
You probably want to implement an interface or an abstract class.
From MSDN
If you anticipate creating multiple versions of your component, create
an abstract class. Abstract classes provide a simple and easy way to
version your components. By updating the base class, all inheriting
classes are automatically updated with the change. Interfaces, on the
other hand, cannot be changed once created. If a new version of an
interface is required, you must create a whole new interface.
If the functionality you are creating will be useful across a wide range of
disparate objects, use an interface. Abstract classes should be used
primarily for objects that are closely related, whereas interfaces are
best suited for providing common functionality to unrelated classes.
If you are designing small, concise bits of functionality, use
interfaces. If you are designing large functional units, use an
abstract class.
If you want to provide common, implemented
functionality among all implementations of your component, use an
abstract class. Abstract classes allow you to partially implement your
class, whereas interfaces contain no implementation for any members.
Abstract Class Example
Cat and Dog can both inherit from abstract class Animal, and this abstract base class will implement a method void Breathe() which all animals will thus do in exactly the same fashion. (You might make this method virtual so that you can override it for certain animals, like Fish, which does not breath the same as most animals).
Interface Example
All animals can be fed, so you'll create an interface called IFeedable and have Animal implement that. Only Dog and Horse are nice enough though to implement ILikeable - You'll not implement this on the base class, since this does not apply to Cat.

Properties in an Interface

In my interface, I have declared a property with setter and getter.
public interface ITestInterface
{
string AProperty { get; set; }
}
When I code my class which inherit that interface, why I need to define these two properties again?
public sealed class MyClass: ITestInterface
{
public string AProperty { get; set; }
}
Because you are not inheriting from an interface, you are implementing the interface. (although they both share same syntax :)
public class MyClass : IMyInterface { ... } //interface implementing
public class MyClass : MyBaseClass { ... } //inheriting from a class
Assume you are inheriting a candy box (not from your ancestors, in programming manner), it is something (not exactly) like you put the candy box in another box, now the outer box (the derived class, the inherited one) is inherited from candy box and have all the things candy box have, but if you want to implement (make) a candy box yourself you must build a box and put some candy in it. This is the way interfaces work.
Your interface definition only tells there is a property with a getter and setter, not how it is implemented. You could use auto-implemented properties, but you are not required to.
Following the interface, this would be a valid implementation:
public sealed class MyClass: ITestInterface
{
public string APROPERTY
{
get { return someField + " hello"; }
set { someOtherField = value; }
}
}
In an interface definition, string AProperty { get; set; } is the declaration of the property, while in a class, it means that the property is auto-implemented.
Short answer
Because interfaces contain no more than a definition of a class, and cannot contain the actual implementation of any member functions. It's by design.
Long answer
First you have to realize that properties are basically get and set member functions with some simplified syntax. The question here is therefore: why can't an interface definition contain an implementation of a member function?
Well, in some languages (most notably: C++) you can.
If you have an inheritance chain, that's basically solved through lookup tables. Say that you have member function 1, then in all the classes in the inheritance chain, there's a table which contains a pointer to function 1. Once you call a member function, the call basically grabs the first entry from the table belonging to the type of your object, and calls that. This thing is called a vtable (and for more details, see here).
Now, in C++, VTables are very transparent to the developer: each class basically has a vtable and there's no such thing as a real 'interface'. This also means that all classes can have implementations and members such as fields. If you have a class with only pure virtual members (e.g. functions without an implementation), you have the C++ equivalent of an 'interface'.
In software engineering, these classes were often called 'interface' classes, because they contain only a definition of what's going on, not the actual implementation. Interfaces have the nice property that they describe functionality without actually going into the details, thereby giving the possibility to put 'boundaries' in your code. There are a lot of use cases for this, including (RPC) communication, a lot of design patterns, and so on.
In C++, a class can derive from multiple classes (multiple inheritance) with and without an implementation. Also, because interfaces are in fact more like 'abstract' classes than like 'interfaces' in C#, this means you can also add functionality there. The vtable that was previously described therefore contains pointers to functions in all the base classes.
The problems with this start when you're starting to add functionality to interface classes. For starters, let's say you have something like this (I'll do this in sort-of C#):
interface A { Foo(); } // basically an interface.
interface B : A { Foo(); } // another interface
class B : A { void Foo() {...} } // implementation of Foo, inherits A
class D : B,C { } // inherits both B, C (and A via both B and C).
What we're interested in here is what happens if you call Foo in class D. For that, we have to construct a vtable for class D. Basically this vtable would look like this:
Foo() -> C::Foo()
This means that if you construct an object of D, and call Foo, you'll end up calling the implementation of Foo in type C:
var tmp = new D();
tmp.Foo(); // calls C::Foo()
It becomes more difficult when we're changing the definition of B into something like this:
class B : A { void Foo() {...} } // changed into an implementation
Again, we try to construct the vtable for class D and we end up with a problem:
Foo() -> C::Foo() or B::Foo()???
The problem we're facing here is: what implementation of Foo are we going to use when calling that member? Also, what constructor are we going to call? And what about destruction order? In C++ there are workarounds for this called virtual inheritance.
While designing .NET and the C# language, they thought about past experiences with multiple inheritance and the implications of virtual inheritance and decided that it's not only a difficult thing to implement, but also very confusing for developers at best. As you've seen, these problems don't exist when you just add interfaces.
So, that's why you cannot have a property (or a method) in your interface.
I think the problem here is, that the same syntax has two different meanings for interfaces and classes. AProperty { get; set; } is in an interface is the declaration-only, in a class it's an automatically implemented interface.
So that term is dependent on the context.
public interface ITestInterface
{
string AProperty { get; set; }
}
Declares the Property, but cannot implement it.
public sealed class MyClass: ITestInterface
{
public string AProperty { get; set; }
}
Implements the interface, where the property is automatically implemented (which only works for classes).
Interface contain property signatures not the actual definitions. You are actually requesting for any class implementing ITestInterface to implement get and set for AProperty. See this and this for more details.
As others say interface is just a container for your methods and properties signatures. It needs implementation but this implementation signature will be perfectly match with one that is used in interface. Also it guarantees that all of this members can be accessed in a class instance as they are by default public properties and without implementation program will not compile at all.
Let's say you have interface:
public interface ITestInterface
{
string AProperty { get; }
}
and class that implements it:
class MyClass : ITestInterface
{
public string AProperty { get { if (DateTime.Today.Day > 7) return "First week of month has past"; return "First week of month is on"; } }
}
It's not possible to use auto-implemented properties and not possible to add setter in this class because interface property lacks set accessor and auto-implemented properties requires that interface contains auto-implemented properties signature ({ get; set;}). So in your example interface just declares properties and that's it.
Just by knowing what interfaces class has inherited you know what members are there and if you just want to use (or allow user to use) some of this methods (not allowing to change anything though) you can always upcast your class instance to one of these interface types and pass it as a parameter.
I think the confusion here comes from the fact that auto properties (just the get and or set declarations) look the same in the interface and the implementation. The interface is merely a declaration (contract) of what a class must provide in order to be deemed an implementer of the interface. It is much clearer if you consider a method declaration in an interface vs its implementation in a class.
Interface = requirements;
Class = how those requirements are fulfilled
public interface ITestInterface
{
string GetAProperty();
}
public class MyClass : ITestInterface
{
public string GetAProperty()
{
// Do work...
return "Value";
}
}

Why would you mask a base class member?

I have just learned how to mask a base class member (using new) but am missing the point as to why I would want to do that. Does masking provide us with a certain level of protection as is the case in using encapsulation? Please advise.
You will very rarely use "new" to mask a base class member.
It's mainly used for the cases where the derived class had the member first, and then it was added to the base class --- the same name for a different purpose. The new is there to that you acknowledge that you know you are using it differently. When a base member is added in C++, it just silently merges the existing method into the inheritance chain. In C#, you will have to choose between new and override, to show you know what is happening.
It's not just used for masking. It actually breaks the inheritance chain, so if you call the base class method, the method in the derived class will not be called (just the one in the base class).
You're essentially creating a new method that has nothing to do with the base class method. Hence the "new" keyword.
Keeping that in mind the "new" keyword can be used if you want to define a method with the same signature as a base type method, but having a different return type.
The only valid safe examples that I've come across is being more specific with return types or providing a set accessor on a property. I'm not saying those are the only ones, but that's all I've found.
For example, suppose you have a very simple base that looks like this:
public abstract class Base
{
public string Name { get; protected set; }
public Base(string name)
{ Name = name; }
}
You could have a derived that looks more like this:
public class Derived : Base
{
public new string Name
{
get { return base.Name; }
set { base.Name = value; }
}
public Derived(string name) : base(name)
{ }
}
Assuming business rules allows this one specific Derived to have a changeable name, I believe this is acceptable. The problem with new is that it changes behavior depending on what type the instance is viewed as. For example, if I were to say:
Derived d = new Derived("Foo");
d.Name = "Bar";
Base b = d;
b.Name = "Baz"; // <-- No set available.
In this trivial example, we're fine. We are overriding the behavior with new, but not in a breaking way. Changing return types requires a bit more finesse. Namely, if you use new to change a return type on a derived type, you shouldn't allow that type to be set by the base. Check out this example:
public class Base
{
public Base(Base child)
{ Child = child; }
public Base Child { get; private set; }
}
public class Derived
{
public Derived(Derived child) : base(child)
{ }
public new Derived Child
{ get { return (Derived)base.Child; } }
}
If I could set Child on the Base class, I could have a casting problem in the Derived class. Another example:
Derived d = new Derived(someDerivedInstance);
Base b = d;
var c = b.Child; // c is of type Base
var e = d.Child; // e is of type Derived
I can't break any business rules by treating all of my Derived classes as Bases, it's just convenient to not type check and cast.
I have just learned how to mask a base class member (using new)
FYI this feature is usually called "hiding" rather than "masking". I think of "masking" as clearing bits in a bit array.
am missing the point as to why I would want to do that.
Normally you don't want to. For some reasons to use and not use this feature, see my article on the subject from 2008:
http://blogs.msdn.com/b/ericlippert/archive/2008/05/21/method-hiding-apologia.aspx
Does masking provide us with a certain level of protection as is the case in using encapsulation?
No, it does not.
What you are referring to is called Name Hiding. It is mostly a convenience feature. If you are inheriting from a class for which you do not control the source using new will let you change the behavior of a method even if it wasn't declared as virtual (or completely change the signature if it is virtual). The new keyword simply suppresses a compiler warning. You are basically informing the compiler that you are intentionally hiding the method from a parent class.
Delphi had the reintroduce keyword for the same reason.
What does this buy you other than a suppressed warning? Not a whole lot. You can't access the new method from a parent class. You can access it from an interface if your child class directly implements the interface (as apposed to inheriting it from its parent class). You can still call the parent class' member from the child. Any additional descendants of your class will inherit the new member rather than the one in the parent.
This is actually called member hiding. There are a couple of common scenarios where this can be appropriately used.
It allows you to work around versioning issues in which either the base or derived class author unwittingly creates a member name that collides with an existing identifier.
It can be used to simulate covariance on return types.
Regarding the first point...it is possible that an author of a base class could later add a member with the same name as an exisiting member in a derived class. The base class author may not have an knowledge of the derived classes and thus there is no expectation that she should avoid name collisions. C# supports the independent evolution of class hierarchies using the hiding mechanisms.
Regarding the second point...you may want a class to implement an interface that dictates a certain method signature and so you are locked into returning instances of a certain type only while at the same time you have subclassed that type and would really like for callers to see the concrete type instead. Consider this example.
public interface IFoo { }
public class ConcreteFoo { }
public abstract class Base
{
private IFoo m_Foo;
public Base(IFoo x) { m_Foo = x; }
public IFoo Foo { get { return m_Foo; } }
}
public class Derived
{
public Derived(ConcreteFoo x) : base(x) { }
public new ConcreteFoo Foo { get { return (ConcreteFoo)base.Foo; } }
}

How to make 2 incompatible types, but with the same members, interchangeable?

Yesterday 2 of the guys on our team came to me with an uncommon problem. We are using a third-party component in one of our winforms applications. All the code has already been written against it. They then wanted to incorporate another third-party component, by the same vender, into our application. To their delight they found that the second component had the exact same public members as the first. But to their dismay, the 2 components have completely separate inheritance hierarchies, and implement no common interfaces. Makes you wonder... Well, makes me wonder.
An example of the problem:
Incompatible Types http://www.freeimagehosting.net/uploads/f9f6b862f1.png
public class ThirdPartyClass1
{
public string Name
{
get
{
return "ThirdPartyClass1";
}
}
public void DoThirdPartyStuff ()
{
Console.WriteLine ("ThirdPartyClass1 is doing its thing.");
}
}
public class ThirdPartyClass2
{
public string Name
{
get
{
return "ThirdPartyClass2";
}
}
public void DoThirdPartyStuff ()
{
Console.WriteLine ("ThirdPartyClass2 is doing its thing.");
}
}
Gladly they felt copying and pasting the code they wrote for the first component was not the correct answer. So they were thinking of assigning the component instant into an object reference and then modifying the code to do conditional casts after checking what type it was. But that is arguably even uglier than the copy and paste approach.
So they then asked me if I can write some reflection code to access the properties and call the methods off the two different object types since we know what they are, and they are exactly the same. But my first thought was that there goes the elegance. I figure there has to be a better, graceful solution to this problem.
My first question was, are the 2 third-party component classes sealed? They were not. At least we have that.
So, since they are not sealed, the problem is solvable in the following way:
Extract a common interface out of the coinciding members of the 2 third-party classes. I called it Icommon.
public interface ICommon
{
string Name
{
get;
}
void DoThirdPartyStuff ();
}
Then create 2 new classes; DerivedClass1 and DerivedClass2 that inherit from ThirdPartyClass1 and ThirdPartyClass2 respectively. These 2 new classes both implement the ICommon interface, but are otherwise completely empty.
public class DerivedClass1
: ThirdPartyClass1, ICommon
{
}
public class DerivedClass2
: ThirdPartyClass2, ICommon
{
}
Now, even though the derived classes are empty, the interface is satisfied by the base classes, which is where we extracted the interface from in the first place.
The resulting class diagram looks like this.
alt text http://www.freeimagehosting.net/uploads/988cadf318.png
So now, instead of what we previously had:
ThirdPartyClass1 c1 = new ThirdPartyClass1 ();
c1. DoThirdPartyStuff ();
We can now do:
ICommon common = new DerivedClass1 ();
common. DoThirdPartyStuff ();
And the same can be done with DerivedClass2.
The result is that all our existing code that referenced an instance of ThirdPartyClass1 can be left as is, by just swapping out the ThirdPartyClass1 reference for a ICommon reference. The ICommon reference could then be given an instance of DerivedClass1 or DerivedClass2, which of course in turn inherits from ThirdPartyClass1 and ThirdPartyClass2 respectively. And all just works.
I do not know if there is a specific name for this, but to me it looks like a variant of the adaptor pattern.
Perhaps we could have solve the problem with the dynamic types in C# 4.0, but that would have not had the benefit of compile-time checking.
I would be very interested to know if anybody else has another elegant way of solving this problem.
If you're using .Net 4 you can avoid having to do alot of this as the dynamic type can help with what you want. However if using .Net 2+ there is another (different way) of achieving this:
You can use a duck typing library like the one from Deft Flux to treat your third party classes as if they implemented an interface.
For example:
public interface ICommonInterface
{
string Name { get; }
void DoThirdPartyStuff();
}
//...in your code:
ThirdPartyClass1 classWeWishHadInterface = new ThirdPartyClass1()
ICommonInterface classWrappedAsInterface = DuckTyping.Cast<ICommonInterface>(classWeWishHadInterface);
classWrappedAsInterface.DoThirdPartyStuff();
This avoids having to build derived wrapper classes manually for all those classes - and will work as long as the class has the same members as the interface
What about some wrappers?
public class ThirdPartyClass1 {
public string Name {
get {
return "ThirdPartyClass1";
}
}
public void DoThirdPartyStuff() {
Console.WriteLine("ThirdPartyClass1 is doing its thing.");
}
}
public interface IThirdPartyClassWrapper {
public string Name { get; }
public void DoThirdPartyStuff();
}
public class ThirdPartyClassWrapper1 : IThirdPartyClassWrapper {
ThirdPartyClass1 _thirdParty;
public string Name {
get { return _thirdParty.Name; }
}
public void DoThirdPartyStuff() {
_thirdParty.DoThirdPartyStuff();
}
}
...and the same for ThirdPartyClass2, then you use the wrapper interface in all your methods.
Add an interface. You could add one wrapper (that implements the interface) for each of the 3rd parties.
Anyway, if you have the code of those 3rd parties, you could skip the wrapper thing and directly implement the interface. I'm quite sure you don't have the source, though.

Categories

Resources