Is it possible to select a namespace for classes at runtime. We have two copies of auto generated objects in different namespaces. Here is an example:
Namespace1
ClassA
ClassB
Namaspace2
ClassA
ClassB
Formerly, the code is simple like below
using Namespace1
...
ClassA.AMethod()
However, we need to select namespace at runtime using a condition variable. Is there a way to define a GetNamespace() method and use it like below or is there any other way you recommend?
GetNamespace().ClassA.AMethod()
Cheers,
Burak
As far as I know, there is no way to dynamically select the namespace, but I think you're in the perfect situation to use a factory. To do so, all your A classes must derive from an abstract one:
namespace Common {
public abstract class AbsA
{
//...
}
public class MyFactory
{
public MyFactory()
{
//...
}
public AbsA getA()
{
AbsA a;
if (condition)
a = new Namespace1.A();
else
a = new Namespace2.A();
return a;
}
}
}
Then you ask your factory for object creation:
MyFactory factory = new MyFactory();
labelMessage.Text = factory.getA().Something;
This complicates your structure a bit, but also makes it more coherent.
Two types from different namespaces are entirely different types as far as the CLR is concerned. Basically you'd need to consider the same solutions as you would for picking between any other arbitrary types... e.g. making both classes implement the same interface, and instead of GetNamespace() returning a namespace, it would have to return the object itself.
Given that you can:
var type = Type.GetType("Namespace1.ClassA");
object instance = Activator.CreateInstance(type);
If you then want to invoke methods on that instance, you need to either cast it to a common interface, or get a MethodInfo instance to invoke. If you control the generation of the classes, I would recommend the interface approach:
public interface IClassA
{
void AMethod();
}
namespace Namespace1
{
public class ClassA : IClassA
{ /* Stuff... */ }
}
That way, you need only:
var type = Type.GetType("Namespace1.ClassA");
IClassA instance = (IClassA)Activator.CreateInstance(type);
instance.AMethod();
Most autogenerated classes using tools such as Linq-to-Sql, Entity Framework, and even WCF proxies are created as partial, which means you can create an additional file, e.g. ClassA.partial.cs and add more to your class declarations without modifying the auto-generated class:
partial class ClassA : IClassA { }
Related
Is there way to convert the interface implementation object from one namespace to another since both are having the same interface but only the namespace is differing?
Use case is like below
namespace namespaceA
{
Public Interface IInterface
{
Method1();
Method2();
}
}
namespace namespaceB
{
Public Interface IInterface
{
Method1();
Method2();
}
}
We get two kind of objects.
namespaceA.IInterface object - new implementation
namespaceB.IInterface object. - exists as a part of legacy implementation.
We wanted to handle only one object in the code i.e. namespaceA.IInterface object, based on the new implementation.
But due to legacy implementation we get namespaceB.IInterface object also.
But we don’t want to any specific handling for legacy object and we wanted to handle in the same way as new object and implementation.
So if we get an namespaceB.IInterface object, is there way to convert/cast it to namespaceA.IInterface object provided that interface definitions are same but only exists in a different namespace?
So the code need not worry only about the handling of legacy object.
No - there are two completely different types with no relationship. Just because they have the same member names does not mean that you can cast from one to the other.
You could possibly use an adapter, though:
public class Adapter: namespaceA.IInterface
{
private namespaceB.IInterface target;
public Adapter(namespaceB.IInterface target)
{
this.Target = target
}
public void Method1() {this.Target.Method1();}
public void Method2() {this.Target.Method2();}
}
I´d go with inheriting your new interface from your legacy-one so that every object implementing the legacy-interface also implements the new one and thus can easily be cast to it. This of course assumes the new one has the exact same members. Otherwise you would need to add the implementation for INew to all of your classes, which I assume you want to avoid:
interface ILegacy : INew { /* completely empty */ }
interface INew
{
Method1();
Method2();
}
You can even make the ILegacy-interface Obsolete to be replaced by INew.
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.
I have searched for an answer to accomplish this, but I haven't found anything: I want an interface's method to return an object of the type of the class which implemented it. For example:
interface InterfaceA {
public static returnValue getObjectFromDatabase(); //What do i need to put as returnValue?
}
Then, if I have two classes (for example, ClassA and ClassB) that implement it, I would like to have:
ClassA obj1 = ClassA.getObjectFromDatabase(); //return object of class ClassA
ClassB obj2 = ClassB.getObjectFromDatabase(); //return object of class ClassB
Thank you, in advance.
What you want to do here won't work for two reasons:
Interfaces can't have static members
Interfaces need to specify the return types of their methods. An interface shouldn't know the types of all the members implementing it, that defeats the point and in many cases would be unachievable.
Moreover, if you did manage to do this, it still wouldn't be good design, because it violates the single responsibility principle. You can find plenty of information on this by googling it or looking around this site, but the idea- as indicated by the name- is that a class should only have a single purpose which it is responsible for.
So imagine that your class was, for example, an Employee class. That class has a pretty clear responsibility, it should be responsible for holding information and functionality related to an Employee in a company. It might have members like FirstName, GivePromotion(), etc. So it'd be strange to now make this class also take responsibility for its own database access.
So how this is achieved would be with another class which is responsible for retrieving objects from the database. One common design pattern for this is the repository pattern. You'll also probably want to take advantage of generics. So you repository interface might look like:
public interface IRepository<T>
{
T GetFromDatabase()
}
Which you can then implement with a generic repository:
public class Repository<T> : IRepository<T>
{
T GetFromDatabase()
{
//Your actual code for database retrieval goes here
}
}
Or, if the database retrieval code is very different for some or all classes, you can implement with a specific repository:
public class EmployeeRepository : IRepository<Employee>
{
Employee GetFromDatabase()
{
//Your actual code for database retrieval goes here
}
}
One approach is to use generics:
class Program
{
interface MyInterface<SomeType>
{
SomeType getObjectFromDatabase ();
}
class A : MyInterface<A> { public A getObjectFromDatabase () { return new A (); } }
class B : MyInterface<B> { public B getObjectFromDatabase () { return new B (); } }
class Program2
{
static void Main ()
{
A a1, a2;
a1 = new A ();
a2 = a1.getObjectFromDatabase ();
B b1, b2;
b1 = new B ();
b2 = b1.getObjectFromDatabase ();
}
}
}
I want an interface's method to return an object of the type of the class which > implemented it
You seem to miss the point of interfaces: an Interface shouldn't have any knowledge about its implementers. Interface exposes contracts and that's it.
Also, from your example, I can see that you are trying to create a static method but interfaces and static are far away from each other. Interfaces are tied with instances, not the type.
I have a repository class that uses NPoco/PetaPoco to access data which reads from a common content table.
create table Content (
Id int not null identity primary key,
Type tinyint not null,
...
)
Then I have an abstract ContentBase class that other types inherit. The main difference between inherited types being the value of that type DB column value. They do have some additional columns per concrete content type, but that's not relevant here.
So. In order for my repository class to return any of the actual concrete classes I wanted to write a medhod:
public TContent Create<TContent>(string name, ...)
{
...
// SP executes a few insers and returns newly created data instance
return db.Single<TContent>(
new Sql.Builder.Append(";exec dbo.CreateContent #Type, #Name, ...", new {
Type = TContent.Type, // this is the problem
Name = name,
...
}));
}
As you can see I would require my base abstract class to define a static member to get the actual type value that should be accessible through generic type specification. And inheriting classes should set it according to their concrete type implementation.
The problem is of course that there's no such thing as abstract static members in C#.
How should I approach this problem in a way so that my repository will be able to provide Type value on its own without me providing it explicitly with the call? I would only like to provide generic class when calling it and get back correct concrete type.
Why does it have to be static member?
My method doesn't get an object instance of a particular type but it should create one. That's why I can't really have an instance member Type and read from that one while executing my repository method.
A possible start
As static members are shared among all instances and if this is base class all inheriting classes share the same member unless this class is generic. In that case we get a static member per generic type.
So I was thinking of adding an additional class between the base abstract and concrete classes:
public abstract class ContentBase
{
...
}
public abstract class ContentBase<TConcrete>
where TConcrete: ContentBase<ContentBase> // is this constraint ok?
{
public static ContentType Type = ???;
}
and then concrete classes:
public class ContentOne : ContentBase<ContentOne>
{
???
}
And as said I should be able to call my repository method as:
repo.Create<ContentOne>(name, ...)
where within this method repository should be able to access static member of generic type provided by the call...
Even with your idea of having an abstract ContentBase class, you won't be able to access a custom behavior for each derived class; here is a small test i tried to see if your idea could be used:
public abstract class ContentBase<T>
{
public static Func<string> TypeLocator { get; set; }
static ContentBase()
{
TypeLocator = () => typeof(T).Name;
}
}
public class Content1 : ContentBase<Content1> {
private static string Content1Type = "The type of Content 1";
static Content1()
{
TypeLocator = () => Content1Type;
}
}
public class Content2 : ContentBase<Content2> {}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Content1.Type => " + GetObject<Content1>()); // Content1
Console.WriteLine("Content2.Type => " + GetObject<Content2>()); // Content2
}
private static string GetObject<TContent>() where TContent: ContentBase<TContent>
{
var typeLocator = typeof(ContentBase<TContent>).GetProperties()[0].GetValue(null, null) as Func<string>;
return typeLocator.Invoke();
}
}
The best you can get is the type of the TContent, which may be enough for you to explore the mapping proposition below.
I don't really see a way to implement abstract static members, but you could resort to an external registering dictionary living as a singleton throughout your program which would be used as the mapper between your Type and your Type.DBType
public TContent Create<TContent>(string name, ...)
{
...
// SP executes a few insers and returns newly created data instance
return db.Single<TContent>(
new Sql.Builder.Append(";exec dbo.CreateContent #Type, #Name, ...", new {
Type = RegisteredTypes[typeof TContent],
Name = name,
...
}));
}
Unfortunately the answer of "You Can't!" seems to have a concrete reason with no obvious workaround until C# 8 where it is directly supported.
Static members of non-static classes don't really belong to the same class as their non-static counterparts. The static parts really belong to a completely different class (a static class) whose name is made up by, and only known to, the compiler.
The slight-of-hand that the compiler plays to hide this fools you into thinking that it should be possible. If the compiler didn't hide the fact that there really is no such thing as a class with both static and non-static members, it would be more obvious that the name of the static class is unknown to the non-static class in the same way that references to any other classes referenced by your class are not directly available.
As of C#-8 you can define static methods (and therefore properties but not fields) in an interface so the problem is completely solved if you are not trapped behind a legacy barrier.
I've tried to understand some of the posts of similar, but don't quite understand their purposes and thought I'd explain my own...
I have a class -- fully defined with code with properties, and methods. Many methods are virtual to be overriden by further derived class. So, I have something like the following
Class_Main
-- Class_A : Class_Main
-- Class_B : Class_Main
-- Class_C : Class_Main
-- Class_D : Class_Main
I then need to define one more class that can be dynamically derived from A-D... such as:
Class_X : Class_A (or Class_B or Class_C or Class_D )
as I have additional properties and methods within the Class_X. Since C# can't derive from two actual classes, but can use interfaces, but you can't have code in an interface, just abstract signatures, how might I go about doing such implementation.
Thanks
What you are describing sounds a bit like duck typing. This isn't available in C#, as it is a statically-typed language. Perhaps when C# 4 comes around, dynamic will give you what you are looking for.
If Class_X needs to be "filled in" with functionality from those classes, it would be common to pass that into the class at the time of instantiation:
public class Class_X {
private Class_Main _impl;
public Class_X(Class_Main impl) {
_impl = impl;
}
}
Class_X classXA = new Class_X(new Class_A());
Class_X classXB = new Class_X(new Class_B());
At this point, your Class_X instances have access to the Class_Main properties & methods for all derived classes. This doesn't make Class_X an aggregate, just enables you to use the runtime behavior of any Class_Main from within Class_X (through the _impl object).
Extend from one class and include the other class within Class X, and just have adapter methods to map directly to the class inside.
So, now exactly C#, just prototyping:
class ClassA {
public void FunctionClassA(...) { ... }
public void FunctionClassB(...) { ... }
}
class ClassX : ClassB {
private ClassA classa;
public ClassX() {
classa = new ClassA();
}
public void FunctionClassA(...) { classa.FunctionClassA(...); }
}
So, ClassX now has one function inherited (by appearance) from ClassA, and contains all the methods of ClassB.