It's possible pass subclass of superclass in <T>? - c#

I have a class named GenericDao
internal class GenericDao<T> : IGenericDao<T> {
}
The two class of objects:
public class Empresa {
}
public class Assessoria : Empresa {
}
And i have one EmpresaDao:
public class EmpresaDao {
private GenericDao<Empresa> parent { get; set; }
public EmpresaDao() {
this.parent = new GenericDao<Empresa>();
}
}
How to instantiate the GenericDao using the subclass Assessoria? I do something like this, but not work:
public class EmpresaDao {
private GenericDao<Empresa> parent { get; set; }
public EmpresaDao(Type type) {
if (type == typeof(Assessoria)) {
this.parent = new GenericDao<Assessoria>();
} else {
this.parent = new GenericDao<Empresa>();
}
}
}

In short, you can't, really. However, you can cheat a little if you use a base interface that is not generic, or you use C# 4 and use a base interface that is generic, but with a covariant or contravariant (depending on need) type parameter. For the first case:
interface IGenericDaoBase {
}
interface IGenericDao<T> : IGenericDaoBase {
}
public class EmpresaDao {
private IGenericDaoBase parent { get; set; }
public EmpresaDao(Type type) {
// same as before
}
}
Admittedly, it might be better to rethink your design. Perhaps EmpresaDao can take a generic parameter itself, which would be used like so:
public class EmpresaDao<T> where T : Empresa {
private GenericDao<T> parent { get; set; }
public EmpresaDao() {
this.parent = new GenericDao<T>();
}
}
EDIT: In fact, the more I think about it, the more I believe this latter solution is the way to go. The type parameter in the constructor is fulfilling the same role as the type parameter on the class signature. So you won't have to change the calling code much, except to pass in a generic parameter instead of a Type object.

It is a good thing that your try don't work, you would introduce a bug if it did.
Suppose I have variables a, b both of type EmpresaDao. a is initilized with a Empresa parent and b is initialized with a Assessoria parent. Since a and b are of the same type, it should be possible to use one in place of the other everywhere. Suppose Assessoria but not Empresa has a method assess(). But you expect b.parent to be Assessoria so you want to call b.parent.assess() but you cannot call a.parent.assess() Which means a and b should not be of the same type in the first place.
The solution depends on whether you will ever call .parent.assess() :
a) If you will never call .parent.assess() within EmpresaDao class, let compile time type of the parent always be Empresa. Here is a solution :
public class EmpresaDao
{
private Empresa parent {get; set; }
public EmpresaDao(Func<Empresa> parentConstructor)
{
this.parent = parentConstructor();
}
}
static main()
{
var withEmpresaParent = new EmpresaDao(() => new Empresa());
var withAssessoriaParent = new EmpresaDao(() => new Assessoria());
..
}
b) You will sometimes call .parent.assess() within EmpresaDao class. Then you should make the EmpresaDao generic, as #siride said:
public class EmpresaDao<T> where T : Empresa
{
private T parent {get; set;}
}
However, it is still the case that you will have to make run time checks on parent before calling .parent.assess() Which means there is still something wrong in your design. But there is not enough information to decide what. Maybe .assess() method should be private and not to be called from outside (i.e. Assessoria should be a decorator on Empresa: subclass but with the same interface) Maybe "Empresa holding EmpresaDao" and "Assessoria holding EmpresaDao" should be two different classes. (implementing the same interface, probably)
Edit: Now I realize that, in my solution I mistakenly made the type of parent Empresa or Assessoria instead of GenericDao or GenericDao. I believe my main is still valid though.

Related

How to understand this generic class defination with such type parameters constrain define in C# [duplicate]

Yesterday, I was explaining C#'s generic constraints to my friends. When demonstrating the where T : CLASSNAME constraint, I whipped up something like this:
public class UnusableClass<T> where T : UnusableClass<T>
{
public static int method(T input){
return 0;
}
}
And was really surprised to see it compile. After a bit of thinking, however, I figured it was perfectly legal from the point of view of the compiler - UnusableClass<T> is as much of a class as any other that can be used in this constraint.
However, that leaves a couple of questions: how can this class ever be used? Is it possible to
Instantiate it?
Inherit from it?
Call its static method int method?
And, if yes, how?
If any of these is possible, what would the type of T be?
This approach is widely used in Trees and other Graph-like structures. Here you say to compiler, that T has API of UnusableClass. That said, you can implement TreeNode as follows:
public class TreeNode<T>
where T:TreeNode<T>
{
public T This { get { return this as T;} }
public T Parent { get; set; }
public List<T> Childrens { get; set; }
public virtual void AddChild(T child)
{
Childrens.Add(child);
child.Parent = This;
}
public virtual void SetParent(T parent)
{
parent.Childrens.Add(This);
Parent = parent;
}
}
And then use it like this:
public class BinaryTree:TreeNode<BinaryTree>
{
}
Well.
public class Implementation : UnusableClass<Implementation>
{
}
is perfectly valid, and as such makes
var unusable = new UnusableClass<Implementation>();
and
UnusableClass<Implementation>.method(new Implementation());
valid.
So, yes, it can be instantiated by supplying an inheriting type as the type parameter, and similarly with the call to the static method. It's for instance useful for tree-like structures where you want to generically specify the type of children the node has, while it being the same type itself.
If any of these is possible, what would the type of T be?
They are all possible, and you are the one who is gonna determine what is the type of T.For example let's assume there is a type that inherits from UnusableClass<T>
class Foo : UnusableClass<Foo> { }
Now you can instantiate UnusableClass<Foo> because Foo satisfies the constraint:
UnusableClass<Foo> f = new UnusableClass<Foo>();
Then the type of T become Foo and if you try to call method you need to pass an instance of Foo.

return a class containing generic List

I'm trying to construct a class in c# (5.0) that I can use as a base class and it contains a List, but List could be 2 different types. I want to do the following:
public class BaseC
{
string header { get; set; }
List<object> recs { get; set; }
}
public class derive1: BaseC
{
List<myclassA> recs;
}
public class derive2: BaseC
{
List<myclassB> recs;
}
and importantly what I want to do is return the derived classes from a method in another class:
public BaseC PopulateMyDerivedClass()
{
BaseC b = new BaseC();
b.header = "stuff";
b.recs = FileHelperEngine<myclassB> fhe.ReadStringAsList(x);
}
the main point is that method PopulateMyDerivedClass really does the exact same thing for both derive1 and derive2, just that it returns a different type of list.
I think I need generics. But is that at the base class level and also is PopulateMyDerivedClass then supposed to return a generic? I think that perhaps I am not dealing with polymorhpism, but as you can guess I am new to generics, so struggling.
I think what you want is to make BaseC a generic class and specify the generic when defining the derived classes:
public class BaseC<T>
{
//...
virtual List<T> Recs { get; set; }
}
public class Derived1 : Base<MyClassA>
{
override List<MyClassA> Recs { get; set; }
}
Good point by Alexei Levenkov:
Usual note: DerivedX classes in this case will not have common parent unlike original sample. One may need to add more layer of classes (as non-generic parent of BaseC) or use an interface if DerivedX need to be treated as having common parent/interface.
I get the feeling that your code design could use some rethinking. For one, typically when we talk about "polymorphism", we are usually talking about polymorphic behaviors (methods), rather than members. I think you might want to consider two classes that implement an interface that does all the things you want each class to do (parses data into its own type of list and acts on it as you need it to).
Nevertheless, without getting way into the details of your code, I think something like this might be what you were trying to achieve:
public class BaseC<T>
{
string header { get; set; }
public List<T> recs {get;set;}
}
and
public BaseC<T> PopulateClass<T>()
{
var b = new BaseC<T>();
b.recs = new List<T>();
T first = (T)Convert.ChangeType("1", typeof(T));
b.recs.Add(first);
return b;
}
And to check our sanity:
BaseC<String> d1 = PopulateClass<String>();
System.Diagnostics.Debug.Print(d1.recs.First().ToString());
System.Diagnostics.Debug.Print(d1.recs.First().GetType().ToString());
BaseC<int> d2 = PopulateClass<int>();
System.Diagnostics.Debug.Print(d2.recs.First().ToString());
System.Diagnostics.Debug.Print(d2.recs.First().GetType().ToString());
prints
1
System.String
1
System.Int32

Can an upcasted object be downcasted again without trying a cast for every derived class type of the base class type?

I have case where am given a collection of objects that all derive from the same base class. If I iterate over the collection and check each item's type, I can see that the object is of a derived type and then handle it accordingly. What I would like to know is if there is an easier way of performing the check for the derived type besides what I am already doing. Code repetition typically isn't required, so my current methodology seems a bit off to me.
class A {}
class B : A {}
class C : A {}
class D : C {}
class Foo
{
public List<A> Collection { get; set; }
}
class Bar
{
void Iterate()
{
Foo f = new Foo();
foreach(A item in f.Collection)
{
DoSomething(a);
}
}
void DoSomething(A a)
{
...
B b = a as B;
if(b != null)
{
DoSomething(b);
return;
}
C c = a as C;
if(c != null)
{
DoSomething(c);
return;
}
D d = a as D;
if(d != null)
{
DoSomething(d);
return;
}
};
void DoSomething(B a){};
void DoSomething(C a){};
void DoSomething(D a){};
}
I am working with a web service where every web service must have the same result type.
class WebServiceResult
{
public bool Success { get; set; }
public List<Message> Messages { get; set; }
}
class Message
{
public MessageType Severity { get; set; } // Info, Warning, Error
public string Value { get; set; } //
}
class InvalidAuthorization: Message
{
// Severity = MessageType.Error
// Value = "Incorrect username." or "Incorrect password", etc.
}
class InvalidParameter: Message
{
// ...
}
class ParameterRequired: InvalidParameter
{
// Severity = MessageType.Error
// Value = "Parameter required.", etc.
public string ParameterName { get; set; } //
}
class CreatePerson: Message
{
// Severity = MessageType.Info
// Value = null
public int PersonIdentifier { get; set; } // The id of the newly created person
}
The goal is that we can return as many different types of messages back to the client as we want. Instead of getting a single message per web service call, the callee can know about all of their mistakes/successes in a single trip and to eliminate string parsing specific information from the message.
I originally though about using generics, but since the web service could have varying message types, the collection was broadened to use the base message class.
It may be possible to move DoSomething to A and have each subclass provide their own implementation:
public abstract class A
{
abstract void DoSomething();
}
void Iterate()
{
Foo f = new Foo();
foreach(A item in f.Collection)
{
item.DoSomething();
}
}
An idea would be to use a generic constraint on your base class or an interface.
public class MyClass<T> where T : BaseClass, IInterface
{
public void executeCode<T>(T param) {};
}
So MyClass<T> takes only a certain type, executeCode will have an idea what methods are exposed and what operations can be performed on the data of the object passed.
This avoids the need to cast because you are specifying a contract that must be followed.
typeof(ParentClass).IsAssignableFrom(typeof(ChildClass));
Return true is the cast is possible.
Also possible this way:
typeof(ParentClass).IsAssignableFrom(myObject.GetType());
But in your example, you actually call a methods for each object type. So you would need the cast anyway, unless you don't mind refactoring to not have a collection of overload.
Something like this if you want to keep the overload:
foreach(A item in f.Collection)
{
Type itemType = item.GetType();
if (typeof(B).IsAssignableFrom(itemType)
DoSomethingB(item);
else if (typeof(C).IsAssignableFrom(itemType)
DoSomethingC(item);
//...
}
EDIT: I like more Lee's answer. Adding virtual/override function to the class type would be a better design and way easier to handle, unless the DoSomething really has nothing to do being in the classes.
Lee is right. Just let the item decide, what to do. It knows it's type best and therefore knows what to do. You might even give some standard implementation, if it is the same as in A, by not making it abstract, but virtual. Be aware though, that the compiler wont ask for an implementation then.
public class A
{
public virtual DoSomething(){"What A needs doning!"}
}
public class B : A
{
public override DoSomething() {"What B needs doing!"}
}
Another way would be the use of Interfaces.
public interface IAinterface
{
void DoSomething();
}
public class A : IAinterface
{
void DoSomething(){...}
}
public class B : IAinterface
{
void DoSomething(){...}
}
This would be more like Lees suggestion, although interfaces and abstract base classes work a bit different in the background.
I usually prefer the upper one, because I usually tend to give the base class some standard behavior and only implement derived classes, when there is something different.

c# - cast generic class to its base non-generic class

I have following classes:
public abstract class CustomerBase
{
public long CustomerNumber { get; set; }
public string Name { get; set; }
}
public abstract class CustomerWithChildern<T> : CustomerBase
where T: CustomerBase
{
public IList<T> Childern { get; private set; }
public CustomerWithChildern()
{
Childern = new List<T>();
}
}
public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}
The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:
public void WalkHierarchy(CustomerBase start)
{
Print(start.CustomerNumber);
if (start is CustomerWithChildern<>)
{
foreach(ch in start.Childern)
{
WalkHierarchy(ch);
}
}
}
Is there any chance I could get something like this working?
The solution based on suggested has-childern interface I implemented:
public interface ICustomerWithChildern
{
IEnumerable ChildernEnum { get; }
}
public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
where T: CustomerBase
{
public IEnumerable ChildernEnum { get { return Childern; } }
public IList<T> Childern { get; private set; }
public CustomerWithChildern()
{
Childern = new List<T>();
}
}
public void WalkHierarchy(CustomerBase start)
{
var x = start.CustomerNumber;
var c = start as ICustomerWithChildern;
if (c != null)
{
foreach(var ch in c.ChildernEnum)
{
WalkHierarchy((CustomerBase)ch);
}
}
}
You could move the WalkHierarchy method to the base class and make it virtual. The base class implementation would only process the current node. For the CustomerWithChildern<T> class, the override would do an actual walk.
Try this:
if(start.GetType().GetGenericTypeDefinition() == typeof(CustomerWithChildern<>))
I believe that you want to make the lookup for the determination of doing to the walk an interface.
So maybe add an "IWalkable" interface that exposes the information needed to do the walk, then you can create your method checking to see if the passed object implements the interface.
"Is" and "As" only work on fully qualified generic types.
See this MSDN discussion for details including workarounds.
The most common workaround I've seen is to add an interface to the mix that your CustomerWithChildren could implement, and check for that interface.
I think everyone hits this "issue" when first working with generic classes.
Your first problem is hinted at in your question phrasing: an open generic type is NOT the base class to a closed one. There is no OO relationship here, at all. The real base class is CustomerBase. An "open" generic type is like a half-completed class; specifying type arguments "closes" it, making it complete.
While you can do:
Type t = typeof(CustomerWithChildern<>)
the condition
typeof(CustomerWithChildern<>).IsAssignableFrom(CustomerWithChildern<Foo>)
will always be False.
-Oisin
Explicitly with that method, no. However you can achieve the same functionality with an interface. In fact, you could just have your generic class implement IEnumerable. It's also worth noting that your class should also have "where T : CustomerBase" in order to ensure type safety.

Really bizarre C# generics question

This code compiles but looks very strange.
I have a typical and simple parent/child relationship here which is implemented using generics in a very strange way.
But I can't seem to find any other way of doing it.
class SampleObject<T> //I don't want to make this a generic but am forced to
{
//The SampleContainer this object is in
//This must be located in this base class
public SampleContainer<T> Parent { get; set; }
}
class SpecificObject : SampleObject<SpecificObject>
//SampleObject<SpecificObject> !!? This is the bizzare bit
//It seems really strange but necessary for compilation to work
{
}
//A class to contain a List of objects derived from SampleObjects
class SampleContainer<T>
{
public List<T> List;
}
class Start
{
public void Test()
{
SampleContainer<SpecificObject> container = new SampleContainer<SpecificObject>();
SpecificObject o = new SpecificObject(); //create an object
container.List.Add(o); //add it to the list
o.Parent = container; //set its parent
}
}
Can this code be simplified?
This seems to work without the type.
Is this what you were looking for?
class SampleObject //I don't want to make this a generic but am forced to
{
//The SampleContainer this object is in
//This must be located in this base class
public SampleContainer<SampleObject> Parent;//{ get; set; }
}
class SpecificObject : SampleObject
//SampleObject<SpecificObject> !!? This is the bizzare bit
//It seems really strange but necessary for compilation to work
{
}
//A class to contain a List of objects derived from SampleObjects
class SampleContainer<T>
{
public List<T> List;
}
class Start
{
public void Test()
{
SampleContainer<SampleObject> container = new SampleContainer<SampleObject>();
SpecificObject o = new SpecificObject(); //create an object
container.List.Add(o); //add it to the list
o.Parent = container; //set its parent
}
}
In the MSDN documentation, it states that:
When deriving from a generic base
class, you must provide a type
argument instead of the base-class's
generic type parameter:
public class BaseClass<T>
{...}
public class SubClass : BaseClass<int>
{...}
It's probably a constraint that the C# designers set up in the compiler. They require that a derived type must specify the type of the generic argument at compile time. I'm not quite sure why.
Generics can create some unwieldy class hierarchies. However, the syntax for SpecificObject : SampleObject does make sense, since you're stating that the object has a parent relationship. The only other way I could see you do this, would be to split out the hierarchy with an interface. It doesn't buy much, but it may help clarify the intent.
interface IHasParent<T>
{
T Parent { get; set; }
}
public class SpecificObject : IHasParent<SpecificObject>
{
public SpecificObject Parent { get; set; }
}
If you're concerned about how verbose your collection is, you can tame the angle brackets a bit by using:
public SpecificObjectContainer : Container<SpecificObject>
{
}

Categories

Resources