Reputation: 3
I am programming a dll with a factory pattern on C#. The factory receive an enum and return an interface. Depending on the received enum it create different objects and return it encapsulated in the interface. Any class inside the factory implements the interface and its access modifier is internal, except the own interface which is public.
The problem is when i call the dll from the main project. Each object created inside the factory has different properties and do not why i can not access or modify those properties from the main. Some help?
this is the Factory call from the main.
IConfigurator config = ConfigFactory.Instance.CreateConfigurator(Model.First);
This is how the factory works (inside the dll):
public IConfigurator CreateConfigurator(Model model)
{
switch (model)
{
case Model.First:
return (First)new First(model);
case Model.Second:
return (Second)new Second(model);
case Model.Third:
return (Third)new Third(model);
}
}
First, Second and Third has different properties and i am not able to modify it from the interface object received
Thanks.
Upvotes: 0
Views: 1990
Reputation: 1187
The short answer is that you're returning an interface, therefore only the properties that are part of the interface are available until you cast the object to its concrete type.
For example:
public class A : INameable
{
public string Name { get; set; }
public int Age { get; set; }
}
public class B : INameable
{
public string Name { get; set; }
public string Description { get; set; }
}
public Interface INameable
{
string Name { get; set; }
}
public Enum Selector
{
A,
B
}
So if I use a method as follows
public INameable GetINameable(Selector selector)
{
if (selector.Equals(Selctor.A))
return new A { Name = "Name A", Age = 10 };
if (selector.Equals(Selector.B))
return new B { Name = "Name B", Description = "New Instance of B"};
}
I will get an instance of INameable
returned and will only be able to access the Name
property as defined in the interface.
However if I need to access the other properties then I need to cast the returned object to its concrete type as follows:
// This will be an instance of INameable
var obj = GetINameable(Selector.A);
// Now cast as an instance of A
var castObj = obj as A;
// We can now access the Age property
var age = castObj.Age;
Upvotes: 1
Reputation: 26642
The method can have only one return type. Instead of chossing result by enum, create different factory method / factory class for every item.
Sample:
// instead of this
public enum FactoryEnum {
VariantA,
VariantB,
VariantC
}
object Create(FactoryEnum item);
// do this
IMyInterfaceA CreateA();
IMyInterfaceB CreateB();
IMyInterfaceC CreateC();
Upvotes: 0