Get name of class that implements an interface - c#

I have some entities, that may or may not inherit from other objects, but they will implement an interface, lets call it IMyInterface.
public interface IMyInterface {
long MyPropertyName { get; set; }
}
An object will always implement this interface, but it may have been implemented on a class that the object inherits from. How can i get the name of the class that has this interface implemented?
Examples should give these results
public class MyClass : IMyInterface {
}
public class MyHighClass : MyClass {
}
public class MyPlainClass {
}
public class PlainInheritedClass : MyPlainClass, IMyInterface {
}
If i pass in MyClass, it should return MyClass, because MyClass implements the interface.
If i pass in MyHighClass, it should return MyClass, because MyClass was inherited, and it implements the interface.
If i pass in PlainInheritedClass, it should return PlainInheriedClass, because it inherited from MyPlainClass, but that did not implement the interface, PlainInheritedClass did
EDIT/ EXPLAINATION
I am working with entity framework 6. I have created a sort of recycle bin feature, that allows users to delete data on the database, but really it just hides it. In order to use this feature, an entity must implement an interface, which has a particular property against it.
Most of my entities do not inherit from anything, but just implement the interface. But i have a couple of entities that do inherit from another object. Sometimes the object they are inheriting from implement the interface and sometimes the object itself will implement the interface.
When i set the value, i use the entities and entity framework works out which table to update. But when i "unset" the property, i am using my own SQL statements. In order to create my own SQL statements, i need to find out which table has the column i need to update.
I cannot use entity framework to load the entities based on the type only, because .Where doesnt exist on a generic DbSet class.
So i want to create an SQL statement similar to this
UPDATE tableX SET interfaceProperty = NULL WHERE interfaceProperty = X

I was just over thinking the whole thing, the function was very easy. Just encase someone needs something siliar, here it is, i have made it generic. You could always make it an extension instead.
Code just interates all the way down, to the base class, and then checks each class on the way back up through the tree.
public Type GetImplementingClass(Type type, Type interfaceType)
{
Type baseType = null;
// if type has a BaseType, then check base first
if (type.BaseType != null)
baseType = GetImplementingClass(type.BaseType, interfaceType);
// if type
if (baseType == null)
{
if (interfaceType.IsAssignableFrom(type))
return type;
}
return baseType;
}
So i had to call this like so, with my examples
// result = MyClass
var result = GetClassInterface(typeof(MyClass), typeof(IMyInterface));
// result = MyClass
var result = GetClassInterface(typeof(MyHighClass), typeof(IMyInterface));
// result = PlainInheritedClass
var result = GetClassInterface(typeof(PlainInheritedClass), typeof(IMyInterface));

Related

Generic implementation of a factory for classes of different types

We are being provided a set of Entity and Consumer classes. Calling the XConsumer returns an XEntity, while calling the YConsumer returns an YEntity and so on. The APIs for the Consumer classes are identical taking arguments of same type. The Consumer and Entity classes do not inherit from a base class nor implement an Interface. What I would like to achieve is to generically call a factory that returns a desired Entity of a particular type. My current implementation looks like so:
static class Factory<TConsumer> where TConsumer : new()
{
static dynamic Consume(Document document, out List<Error> errors)
{
// Common code before calling any consumer goes here
Stream stream = document.Stream;
dynamic consumer = new TConsumer();
return consumer.Consume(stream, out errors);
}
}
My calling code looks like so
XEntity entity = Factory<XConsumer>.Consume(document, out errors);
Note I’m only in charge of the Factory class and the calling code and not allowed to modify the Entity and Consumer classed. Is there a way to make this better, preferably without using dynamic?
One way to avoid reflection is to use the Adapter pattern.
Basically, what you do is create an interface that contains the common methods and properties of your consumer classes, and create a wrapper class for each consumer that implements this interface.
This way you can implement your method without using dynamic or reflection, and keep it type safe.
The downside is, of course, you are going to have to write (and maintain) a lot more code than what you currently have.
Ideally, you need to get the entity classes changed so that they both implement an interface, eg IEntity. The factory should select the consumer based on some criteria, rather than knowing which consumer you want to use. You can base this decision on the required wntiry return type.
Eg:
// you don't necessarily need this interface but it allows a meaningful
// constraint if you apply it to your 'entity' classes. If you can't apply
// this interface to the entity classes then remove the constraints below
public interface IEntity
{
// things it does
}
public class XEntity : IEntity
{
}
public class YEntity : IEntity
{
}
public interface IConsumer<TEntity> where TEntity : IEntity // remove constraint if required
{
TEntity Consume(Stream stream, out List<Error> errors);
}
public class XConsumer : IConsumer<XEntity>
{
public XEntity Consume(Stream stream, out List<Error> errors);
{
// something
}
}
public class YConsumer : IConsumer<YEntity>
{
public YEntity Consume(Stream stream, out List<Error> errors);
{
// something
}
}
public static class ConsumerFactory
{
// this will now create a consumer instance based on the entity type
public static IConsumer<TEntity> Create<TEntity>() where TEntity : IEntity // remove constraint if required
{
if (typeof(TEntity) == typeof(XEntity))
return new XConsumer;
if (typeof(TEntity) == typeof(YEntity))
return new YConsumer;
throw new Exception("Unsupported type");
}
public static TEntity Consume<TEntity>(Stream stream, out List<Error> errors) where TEntity : IEntity // remove constraint if required
{
return Create<TEntity>().Consume(stream, out errors);
}
}
Usage:
XEntity x = ConsumerFactory.Consume<XEntity>(document, out errors);
YEntity y = ConsumerFactory.Consume<YEntity>(document, out errors);
No reflection is not what I want. I’m marking your response as answer but I’m going to stick with my own implementation. Originally I thought I post this question in case I missed something

Polymorphism, using methods of child classes

I have an interface IRecordBuilder and an abstract class Query with a field protected IRecordBuilder recordBuilder and a method public abstract IList<IRecords> GetRecordsFromResults();.
In Query child classes constructors, I specify a recordBuilder concrete type depending on which child class I am in, for exemple :
recordBuilder = new RecordsPerMonthBuilder(); //RecordsPerMonthBuilder implements IRecordBuilder
I would like to use my recordBuilder field in the implementations of the abstract method above, but the properties in the implementations of IRecordBuilder remains unknown at compile time and i can't use them.
Besides transfering recordBuilder from mother class to each child classes and instantiate it there with the proper type, is there a way to make the polymorphism work here ?
Here are the explanations in code format :
public interface IRecordBuilder
{
IRecords BuildRecord();
}
public class RecordsPerMonthBuilder : IRecordBuilder
{
public IRecords BuildRecord()
{
if(Foo != null) return new FooRecord(Foo); // class FooRecord : IRecord
return null;
}
public string Foo {get; set;}
}
public abstract class Query
{
protected IRecordBuilder recordBuilder;
public abstract IList<IRecords> GetRecordsFromResults();
}
public sealed class ConcreteQuery: Query
{
public ConcreteQuery()
{
RecordBuilder = new RecordsPerMonthBuilder();
}
public override IList<IRecords> GetRecordsFromResults()
{
var recordsList = new List<IRecords>();
recordBuilder.foo = "foo"; // IRecordBuilder does not contain a definition for foo
recordsList.Add(RecordBuilder.BuildRecord());
return recordsList;
}
}
I see three possible solutions for this:
Option 1: In your child class, cast the builder to the concrete type (since the child class created it, it knows the concrete type). If you do that, you might want to make the recordBuilder field readonly and pass it to the base constructor to ensure at compile time that its type cannot be changed.
Option 2: In your child class, keep an additional "strongly typed" reference to the record builder. (In fact, why do you even need the "interface typed" reference at all?)
public sealed class ConcreteQuery: Query
{
private RecordsPerMonthBuilder myBuilder;
public ConcreteQuery()
{
myBuilder = new RecordsPerMonthBuilder();
RecordBuilder = myBuilder;
}
public override IList<IRecords> GetRecordsFromResults()
{
var recordsList = new List<IRecords>();
myBuilder.foo = "foo";
recordsList.Add(myBuilder.BuildRecord());
return recordsList;
}
}
Option 3: Make your base class generic:
public abstract class Query<TBuilder> where TBuilder : IRecordBuilder
{
protected TBuilder RecordBuilder;
public abstract IList<IRecords> GetRecordsFromResults();
}
public sealed class ConcreteQuery : Query<RecordsPerMonthBuilder>
{
...
}
One area of confusion is that your Query class depends explicitly on one implementation of IRecordBuilder, RecordsPerMonthBuilder. The interface IRecordBuilder doesn't have a Foo property, but Query depends on the Foo property. Query is hard-coded to only use RecordsPerMonthBuilder.
It's difficult to see the intent. One way to clear it up is to make sure that any interaction between Query and an implementation of IRecordBuilder is defined in IRecordBuilder. Query should depend on the interface and shouldn't call any properties or methods that aren't in that interface.
If only one implementation of IRecordBuilder requires a Foo, then that value shouldn't be coming from your Query class because Query doesn't know that IRecordBuilder needs a Foo. It shouldn't know what an implementation of IRecordBuilder needs, only what it does.
Here's a way to move it around. You'll see this pattern a lot.
public abstract class Query
{
protected IRecordBuilder RecordBuilder { get; private set; }
protected Query(IRecordBuilder recordBuilder)
{
RecordBuilder = recordBuilder;
}
public abstract IList<IRecords> GetRecordsFromResults();
}
Now it will never know what the implementation of IRecordBuilder is. That's good. It's now impossible for it to depend on anything that's not in the IRecordBuilder interface. Now Query depends on an abstraction, applying the Dependency Inversion principle.
What about RecordsPerMonthBuilder? It depends on a value, Foo. Will every implementation of IRecordBuilder need that? If so you could add it to the interface:
IRecords BuildRecord(string foo);
But if only one implementation needs that value then it shouldn't come from Query, because Query shouldn't know the difference between one IRecordBuilder and another. I can't answer that more specifically because I don't know what Foo is.
Another suggestion: If the inheritance between Query and ConcreteQuery gives you any grief, just don't use inheritance. Sometimes trying to use inheritance creates complications and doesn't give us any benefit in return.

Cast concrete<Interface> to Interface<concrete>

I am getting an object of type Company<IDesignation>. Now I want to cast it to ICompany<Manager>. Run time I know that IDesignation is nothing but "Manager" type.
Is this what you are looking for?
Company comp = new Company();
Manager mgner = new Manager(comp.getManager());
IDesignation manager = mgner;
ICompany company = (ICompany)manager;
Assuming Company is:
public class Company: ICompany, IDesignation //or something?
Using either Generic Type Casting (what u are trying to do) or simply Casting an Interface or object depends on whether you will perform this task explicitly or implicitly (maybe class has pre-defined function to cast it) and as your comment has pointed out... maybe by user or runtime matters or whether or not and/or how you need to instantiate your object so I would really need to see the class implementation in order to be able to provide something that uses type casting in the way you want to perform it.
What you need is Contravariance, i.e. your IEntityDelta generic type parameter needs to be made contravariant.
The only way to do that and for this to work is to have:
public interface IEntityDelta<in T> : IEntityDelta where T : IEntity
Note the in T in the definition.
Check out the in (Generic Modifier) (C# Reference)
Or this Understanding Covariant and Contravariant interfaces in C#
If you're not the creator of that interface and if the IEntityDelta<> is defined w/o the in modifier you're out of luck.
And just to mention that adding in/out modifiers is easier said than done. For that to compile your methods, properties etc. need to satisfy
the conditions of contravariance (or covariance in case of 'out') on that generic type (T) parameter.
And this what your classes, interfaces look like based on your info (which was terrible btw. next time you need to dedicate a bit more time
in providing minimal but complete code that makes sense):
public interface IEntityDelta<in T> : IEntityDelta
where T : IEntity
{
void MakeDelta(T entity); // this is allowed
//T Entity { get; set; } // this won't work
}
public class EntityDelta<T> : IEntityDelta<T>
where T : class, IEntity
{
public T Entity { get; set; }
public EntityDelta(T entity) => Entity = entity;
public void MakeDelta(T entity) { }
}
public interface IEntityDelta { }
public abstract class Entity : IEntity { }
public class Order : Entity { }
public interface IEntity { }
...and usage:
var order = new Order();
EntityDelta<IEntity> orderDelta = new EntityDelta<IEntity>(order);
IEntityDelta<IEntity> idelta = orderDelta;
IEntityDelta<Order> iOrderDelta = orderDelta;

Implement copy/deepcopy on multiple base classes

not sure if this maybe is a codeReview post but here we go:
My goal is to re-implement the way objects are copied within our application. We have multiple base classes:
CoreList<T> // for all list classes
BasicReference // for all reference classes
CoreObject // for all "normal" domain objects
All classes inherit from these base classes. Right now the copy method is implemented on the CoreObject class and will go through the object tree via reflection, looking at each property type and select the correct way to copy the type and finally returning always CoreObject.
There are some problems which I don't like about that approach, which is why I would like to change it:
After copying an domain object you always have to cast it "back" to the original type, for example: Animal = animal.Copy() as Animal;
All logic to copy each type is within the CoreObject class even though it should not know about other base classes.
So my first attempt was to introduce a interface:
public interface IObjectCopy<out T>
{
T Copy();
}
Which then should be implemented on all base classes. Then every class is responsible for the way it is copied. For example (pseudo code):
public class CoreObject : IObjectCopy<CoreObject>
{
public virtual GerCoreObject Copy()
{
foreach (var prop in properties)
{
if (prop.IsNoSimpleType)
{
(prop as IObjectCopy).Copy()
}
}
}
That solves the copy-responsibility problem, in addition inherited classes can take care of the copy logic themselves.
Unfortunately that does not solve the return type, I still have to cast it to the correct type. I did not think of a better solution to solve this. Any ideas?
This problem could be solved in OO using covariant return types. Unfortunately C# does not support covariant return types like Java and C++, requiring it to always break type safety.
Without breaking type safety (casting) in C# this is unfortunately not possible.
Here are two possible options:
//explicit interface implementation
public class Animal : CoreObject, IObjectCopy<Animal>
{
Animal IObjectCopy<Animal>.Copy()
{
return (Animal) base.Copy();
}
}
//does not require an explicit cast
IObjectCopy<Animal> animalCopy = myAnimal;
Animal copiedAnimal = animalCopy.Copy();
//second option: shadow the original method and cast inside the object
public class Animal : CoreObject, IObjectCopy<Animal>
{
public new Animal Copy()
{
return (Animal) base.Copy();
}
}
Animal copy = myAnimal.Copy();
Another option using bounded quantification:
public class CoreObject : IObjectCopy<CoreObject>
{
public CoreObject Copy()
{
return Copy<CoreObject>();
}
protected T Copy<T>()
where T : CoreObject, new()
{
T t = new T();
//implement copy logic:
return t;
}
}
public class Animal : CoreObject, IObjectCopy<Animal>
{
public new Animal Copy()
{
return Copy<Animal>();
}
}
If I understood it correctly, you need Curiously recurring template pattern
public class BaseClass<T> where T : BaseClass<T>
{
public virtual T Clone()
{
// Perform cloning with reflection.
return clone as T;
}
}
Then you just define your class as:
public class EndObject : BaseClass<EndObject>
{
}
EndObject e;
e.Clone() // Will return EndObject type

oops concept query

I have a question related to OOPS concept.
I have a base class
public class BaseClass
{
public int i = 10;
public int x = 30;
public string str = "Hello";
public virtual string Hello()
{
return "Hello of base class called";
}
}
I have a child class
public class ChildClass : BaseClass
{
public int i = 20;
public int z = 90;
public override string Hello()
{
return "Hello of child class called";
}
}
Now i have seen that the below code works fine
BaseClass baseObject = new ChildClass();
and when I type baseObject. then i only see members of BaseClass only.
First question: Can someone advise me on a situation where a developer needs to do this BaseClass baseObject = new ChildClass();?
Second question: If my BaseClass object has a reference to my child class object then why are my child member variables not accessible through this baseObject?
To answer your first question.
Developers do this to provide abstraction over what actual object they are referring to, which provides flexibility and 'loose-coupling' over the code that uses it.
For example (common scenario - which i use a lot), you might have 10 child classes which extend the base class. What if you wanted a method to return each type of child class? Well, without this type of declaration you would need 10 methods. But if you specified the return type of "BaseClass", you could return all the 10 types of child classes from the one method. This technique ties in closely with the user of interfaces.
E.g
public BaseClass GetDynamicChildClass()
{
if (someCondition) return ChildClass();
else if (someOtherCondition) return SomeOtherChildClass();
}
To answer your second question.
You can't see the child properties because you have said "baseObject" is of type "BaseClass" - the compiler has typed the object to this. In order to access the child properties, you need to cast it as the child type:
BaseClass b = new ChildClass();
int x = b.z; // error.
int x = ((ChildClass)b).z; // works - this is a cast, throws exception in bad conversion
ChildClass c = b as ChildClass; // also works, different type of cast, returns null in bad conversion
int x2 = c.z;
This type of concept (polymorphism) is fundamental to Object-Orientated programming. Have a look at this excellent StackOverflow question: Try to describe polymorphism as easy as you can
It explains it in the simplest way possible, without tying it down to any particular programming framework, which in my opinion is the best way to learn OO.
Hope that helps.
When you want to have objects with individual behavior that have a set of common functions. For example you want to put objects of different types into a list.
The underlying type is still ChildClass but you are currently working on a BaseClass type. That is why you only see the members for BaseClass. It is though still possible to convert the BaseClass instance to a ChildClass instance with a cast operation or the 'as' keyword.
When you do
BaseClass baseObject= new ChildClass();
The static declared type of the object is that of "BaseClass".
Hence you can only see the objects of "BaseClass" type.
If you are sure that the object is of ChildClass Type, you can typecast baseObject to "ChildClass" and then use the ChildClass members
((ChildClass) baseObject). - should help intellisense give you the members of the child class.
Using BaseClass baseObject= new ChildClass(); is the base for RunTime polymorphism.
It is very commonly used if you need the overridden child logic to be called but the interface is that of the base class
EDIT : Example of a scenario where you would use it
Class User has derived classes called Employee and 3rdPartyUser
Class User has a virtual method called GetRoleInformation - which is used to obtain Role Info for user from the companies Active directory.
However, for 3rd party user, as the information does not exist in AD, the logic for getting the Role Information involves calling a Web Service to retrieve the data.
In this case, GetRoleInformation is overridden in 3rdPartyUser class
Now, in the program, on the Login Page, once authenticated, i either get back an object of Employee or 3rdPartyUser.
I pass this object to a method with a signature RoleCollection GetRole( User loggedInUser)
Inside this method, without having to determine the type of the user, i just call loggedInUser.GetRoleInformation and depending on whether it is Employee / 3rdPartyUser, the appropriate base / overridden method will be called and Role data will be retrieved from either AD / Web Service.
Long story short :
Advantage of
BaseClass baseObject= new ChildClass();
OVER
ChildClass baseObject= new ChildClass();
is in scenarios when you are not sure of the exact type of child object that is going to be assigned to baseObject variable eg: in this case Employee / 3rdPartyUser
Eg:
BaseClass baseObject= GetLoggedInUser();
where signature of this method is User GetLoggedInUser(string userid)
Otherwise, in an example like yours, where the object is ALWAYS of type "ChildClass", i beleive that there is no advantage to doing it.
The answer of your first questiom :
this type of implementation is common when we are using abstract factory patten for the i wll give u a simple example which is creates a family ford car ..
public class AbstractFactoryExample
{
public AbstractFactoryExample()
{
string type = "";
CarFactory facotry=null;
if (type == "FORD")
{
facotry = new FordCarFactory();
}
ICar MyFamilyCar = facotry.CreateFamilyCar();
ICar MyCityCar = facotry.CreateCityCar();
}
}
public interface ICar
{
}
public abstract class CarFactory
{
public abstract ICar CreateFamilyCar();
public abstract ICar CreateCityCar();
}
public class FordCarFactory : CarFactory
{
public override ICar CreateFamilyCar()
{
return new FordFamilyCar();
}
public override ICar CreateCityCar()
{
return new FordCityCar();
}
}
public class FordFamilyCar : ICar
{
}
public class FordCityCar : ICar
{
}
to your second question :
you are declaring the object as baseclass so it shows only the methods in it only and if you sure about the the generated instance is of type child class
((ChildClass) baseObject)
can solve the problem
please excuse me for my bad english
Here is an example where the only method we care about is in the base class. By using this type of abstraction we can easily add more report types.
public class Report
{
public virtual string ContentType
{
get { return "application/octet-stream"; }
}
public virtual byte[] Build()
{
return new byte[0];
}
public static Report Create(ReportType type)
{
switch (type)
{
case ReportType.Pdf:
return new PdfReport();
case ReportType.Html:
return new HtmlReport();
case ReportType.Doc:
return new DocReport();
case ReportType.Xls:
return new XlsReport();
default:
return new DefaultReport();
}
}
}
Then from the client side we only have to do this:
ReportType type = GetReportTypeFromFormPost();
Report report = Report.Create(type);
// ...
Response.Write(report.Build());
In fact it makes more sense to you, when you use Factory Pattern (http://gsraj.tripod.com/design/creational/factory/factory.html) to instantiate the object. This would abstract out the implementation specific details to different class.

Categories

Resources