C#: simple Multiple-inheritance / mixin replacement? - c#

I have a class from an external library which I need to extend into antoher class. Also the extensions should remain reusable, as I need them also to be implemented in other places.
As neither mixins nor multiple inheritance are supported in C#, whats the common way to solve this?
namespace ExtLib
{
public class Properties
{
public virtual int fieldN { get; set; }
}
}
namespace MyLib
{
public class Extensions
{
public virtual int fieldM { get; set; }
}
}
namespace MyProject
{
public class MyModel
{
// needs to have all fields from ExtLib.Properties AND MyLib.Extensions
}
public class MyOtherModel
{
// needs to have all fields from MyLib.Extensions,
// MyLib.Extensions should be reusable
}
}
I know a solution could be an interface IExtensions, however this leads to alot of duplication as the number of the fields of Extensions and Properties are quite high (and in the development phase they change alot).
Are there any best practices?

How about you just aggregate instances of these classes into MyModel?
public class MyModel
{
private Properties _properties;
private Extensions _ extensions;
public MyModel(Properties properties, Extensions extensions)
{
_properties = properties;
_extensions = extensions;
}
public Properties Prop
{
get { return _properties; }
}
public Extensions Ext
{
get { return _extensions; }
}
}
Alternatively, you can of course get rid of manual backing fields and use auto-implemented properties with a public getter and private setter.
All changes to Properties and Extensions will be automatically reflected in MyModel. Aggregation is a common way of using design patterns in an object oriented manner as opposed to class manner, which regularly uses multiple inheritance.
As for polymorphism issues, you can create a derived class, override any behavior you want and pass an instance of that class into the constructor.

Create an abstract class that is derived from ExtLib, then derive MyProject from your abstract class
namespace ExtLib
{
public class Properties
{
public virtual int fieldN1 { get; set; }
public virtual int fieldN2 { get; set; }
public virtual int fieldN3 { get; set; }
public virtual int fieldN4 { get; set; }
public virtual int fieldN5 { get; set; }
}
}
namespace MyLib
{
abstract class Extensions : Properties
{
public virtual int fieldM1 { get; set; }
public virtual int fieldM2 { get; set; }
public virtual int fieldM3 { get; set; }
public virtual int fieldM4 { get; set; }
public virtual int fieldM5 { get; set; }
}
}
namespace MyProject
{
public class MyModel : Extensions
{
// contains all fields from ExtLib.Properties AND MyLib.Extensions
}
}

Related

Auto implement properties in inherited form

I'm creating a form to manage the reports of my application, the idea is that every report form inherits from this base form. My problem is that it contains several properties that HAVE to be assigned and i need to verify on every child form if I already called all, so... I'm wondering if there is a way to automatically make a call to all those properties.
This is part of the controller code:
public abstract partial class ReportsController()
{
public string Table{ get; set; }
public string Fields{ get; set; }
public string Condition{ get; set; }
public string Group{ get; set; }
public string Order{ get; set; }
public DataGridViewColumnCollection Columns{ get; set; }
public SortedList<string, string> ComboboxFields{ get; set; }
etc...
protected abstract void New();
protected abstract void Edit();
protected abstract void Print();
}
As you can see, methods are not a problem, they are abstract so they will have to be declared (and thanks to Resharper i will be warned if i missed one).
Child form:
public partial class frmReportGuards : ReportsController
{
public frmReportGuards()
{
code...
}
protected override void New()
{
code...
}
other methods...
}
And im looking for this:
public partial class frmReportGuards : ReportsController
{
public frmReportGuards()
{
//Auto assigned properties.
Table = "";
Fields = "";
Condition = "";
Group = "";
Order = "";
Columns = new DataGridViewColumnCollection();
ComboboxFields = new SortedList<string, string>();
}
protected override void New()
{
code...
}
other methods...
}
I don't know if I'm being senseless here :/ and I really need to get out of this doubt and if is possible... then simplify my work.
If your goal is to ensure that your properties are initialized to some default value, just add a constructor to ReportsController and set the properties there.
Now I understand, if you need to enforce implementation you should do it with abstract properties, inherited classes should implement then, and can be implemented with auto-properties:
public abstract class A
{
public abstract int MyProperty { get; set; }
}
public class B : A
{
public override int MyProperty { get; set; }
}
Short answer is not in C#5.0, in C#6.0 you have Auto-Property initializers, but I think that this is not what you are looking for.
Assuming you need a parameterless constructor, you can create an Init abstract method that is called from your base constructor and do a check if your initialization missed a property. There you can throw an exception or show a visual message indicating the failure.
So in base you do:
public abstract partial class ReportsController()
{
public ReportsController()
{
InitializeComponent();
//now your method
Init();
CheckProperties();
}
protected virtual void CheckProperties()
{
if(Table==null)
addVisualErrorMessage("Table property missing");
//and so on
}
protected abstract void Init();
}
But maybe you have to rethink your design and provide a single class with all the properties, so you can create an abstract method that forces you to provide all these important properties overriding a single method:
public class ComplexProperties
{
public string Table{ get; set; }
public string Fields{ get; set; }
public string Condition{ get; set; }
public string Group{ get; set; }
public string Order{ get; set; }
public DataGridViewColumnCollection Columns{ get; set; }
public SortedList<string, string> ComboboxFields{ get; set; }
}
public abstract partial class ReportsController()
{
public ComplexProperties Properties {get; private set;}
public ReportsController()
{
InitializeComponent();
//now your method
Properties= Init();
CheckProperties();
}
protected abstract ComplexProperties Init();
}
In any case I would prefer having a base constructor with parameters:
public abstract partial class ReportsController()
{
public ComplexProperties Properties {get; private set;}
public ReportsController(ComplexProperties properties)
{
Properties=properties;
CheckProperties();
}
}
And then initialize from the constructor:
public partial class MyReport:ReportsController
{
public MyReport():base(new ComplexProperties { Table="",...})
{
}
}
You could implement an interface for the properties that both the abstract base and the child classes need to implement.

Creating Objects where multiple objects have the same properties

My program is starting to get pretty big. and i have found that its starting to do the same thing in multiple area's.
Im trying to figure out how i can make it more efficient.
So i have an object that looks like this
public class TreeViewNode
{
public TreeViewNode()
{
Children = new ObservableCollection<TreeViewNode>();
}
public String Name { get; set; }
public string Description { get; set; }
public ObservableCollection<TreeViewNode> Children { get; set; }
}
i also have another object that looks like this;
public class ComputerObject
{
public String Name { get; set; }
public Int32 UUID { get; set; }
public DateTime Created { get; set; }
public ObservableCollection<Object> Children { get; set; }
}
Both these items need to have some of the same properties..
at the moment they both have the Children Property and the Name Property. but they both need to have some other common properties added to them.
so i have tried something like this.
public class BaseObject
{
public String Name { get; set; }
public ObservableCollection<Object> Children { get; set; }
public string Description { get; set; }
public BaseObject()
{
Children = new ObservableCollection<object>();
}
}
public class ComputerObject: BaseObject
{
public Int32 UUID { get; set; }
public DateTime Created { get; set; }
}
public class TreeViewNode: BaseObject
{
public String IconPath { get; set; }
}
Now this is just a cut down version of what i am implementing, i have alot of objects that share the same properties. and some that dont and mix and match. and i cannot figure out the best implimentation for this.
My Objects are becoming very cluttered, and when i rename a property i find that i have to rename it in several area's and this isnt the way its ment to be.
can someone please advise how i would implement multiple objects that share the same property names?
In my opinion you should not let classes inherit from one baseclass when these childclasses are not related to each other (like #Sriram Sakthivel asked Animal < Dog,Cat) just to share the same properties.
You should determine which classes are related (cat, dog are animals; car, motorcycle are vehicles) and then create baseclasses based on these "groupings".
I would look into decorator pattern. In short, you dont share common properties via inheritance. You make classes that contain common properties, and use these classes as properties in your end classes.
EDIT: Example is actually just a standard composition, it should work nevertheless
E.G.
public class Decorator1
{
public String Name { get; set; }
public ObservableCollection<Object> Children { get; set; }
public string Description { get; set; }
}
public class Decorator2
{
public long Id { get; set; }
}
public class ClassA
{
public Decorator1 TreeNodeImpl;
}
public class ClassB
{
public Decorator1 TreeNodeImpl;
public Decorator2 LongIdImpl;
}

C#: Extracting to an interface a class that has another class inside - or is there a better way?

I have a class below, i have extracted all the properties to a Interface but i don't seem to be able to extract it... Obviously create a new object like
ITestItem item = new TestItem();
doesn't give me access to Properties which is an instance of Meta class.
I also wanted to stop anyone from create an instance of Meta class outside of TestItem... i tried marking it as internal but that would allow me because Properties is public.
Also i am unsure whether i need to have an interface for META??
here is my class... can anyone help?
public class TestItem : ITestItem
{
public bool Enabled { get; set; }
public Meta Properties = new Meta();
public List<int> Items { get; set; }
public class Meta
{
internal Meta
{
}
public string Name { get; set; }
}
public TestItem()
{
this.Items = new List<int>();
}
}
EDIT
I have uppdated the class above to include an internal constructor for Meta so it can't be instanciated outside the class.
Here is my interface i have (as suggested by giddy)... It says now that it doesn't implement Properties
public interface ITestItem
{
bool Enabled { get; set; }
Meta Properties { get; set; };
List<int> Items { get; set; }
}
So you would:
Not want to maybe use the term extract to interface, maybe your idea about interfaces is a little wrong. You want to do some reading here.
Define the Meta class inside the Test class. Mark the constructor internal or private depending on where you want to create an instance.
Make a property that exposes the Meta class outside of the Test class
public class TestItem : ITestItem
{
public TestItem()
{
this.Properties = new Meta();//set it from here
this.Items = new List<int>();
}
public bool Enabled { get; set; }
//make it private set if you don't want an outsider setting it
public Meta Properties {get;private set}
public List<int> Items { get; set; }
public class Meta
{//make it private if you only create an instance here.
internal Meta(){}
public string Name { get; set; }
}
}
You also add the Meta property to your interface:
public interface ITestItem
{
bool Enabled { get;set;}
Meta Properties { get;set;}
List<int> Items { get;set;}
void ScheduleItem();
}
You may try this one. Its compiled in VS2010. It is better anyway to extract an interface for Meta also for the sake of "decoupling classes" to allow unit testing. Please search and read about - "decoupling classes".
public class Meta { // Do not make this class a child class for flexibility and testing purposes.
public string Name { get; set; }
}
public class IMeta {
string Name { get; set; }
}
public class TestItem : ITestItem {
public TestItem() {
this.Meta = new Meta();
this.Items = new List<int>();
public bool Enabled { get; set; }
public IMeta Meta { get; internal set; }
public List<int> Items { get; set; }
}
public interface ITestItem {
bool Enabled { get; set; }
IMeta Meta { get;}
IList<int> Items { get; set; }
}

Alternatives to nested interfaces (not possible in C#)

I'm using interfaces in this case mostly as a handle to an immutable instance of an object. The problem is that nested interfaces in C# are not allowed. Here is the code:
public interface ICountry
{
ICountryInfo Info { get; }
// Nested interface results in error message:
// Error 13 'ICountryInfo': interfaces cannot declare types
public interface ICountryInfo
{
int Population { get; }
string Note { get; }
}
}
public class Country : ICountry
{
CountryInfo Info { get; set; }
public class CountryInfo : ICountry.ICountryInfo
{
int Population { get; set; }
string Note { get; set; }
.....
}
.....
}
I'm looking for an alternative, anybody would have a solution?
VB.NET allows this. So, you can create a VB.NET assembly only with the interface definitions that you need:
Public Interface ICountry
ReadOnly Property Info() As ICountryInfo
Public Interface ICountryInfo
ReadOnly Property Population() As Integer
ReadOnly Property Note() As String
End Interface
End Interface
As for the implementation, C# does not support covariant return types, so you must declare your class like this:
public class Country : ICountry {
// this property cannot be declared as CountryInfo
public ICountry.ICountryInfo Info { get; set; }
public class CountryInfo : ICountry.ICountryInfo {
public string Note { get; set; }
public int Population { get; set; }
}
}
If the end goal is to use this with dependency injection, what's wrong with injecting them into each other instead of nesting?
public interface ICountry
{
ICountryInfo Info { get; }
}
public interface ICountryInfo
{
int Population { get; set; }
string Note { get; set; }
}
and implement as:
public class Country : ICountry
{
private readonly ICountryInfo _countryInfo;
public Country(ICountryInfo countryInfo)
{
_countryInfo = countryInfo;
}
public ICountryInfo Info
{
get { return _countryInfo; }
}
}
public class CountryInfo : ICountryInfo
{
public int Population { get; set; }
public string Note { get; set;}
}
Then once you set up your bindings for ICountry & ICountryInfo, CountryInfo will inject into Country whenever Country is injected.
You could then restrict the binding, if you wanted, to only inject CountryInfo into Country and nowhere else. Example in Ninject:
Bind<ICountry>().To<Country>();
Bind<ICountryInfo>().To<CountryInfo>().WhenInjectedInto<Country>();
You can use namespaces like this:
namespace MyApp
{
public interface ICountry { }
namespace Country
{
public interface ICountryInfo { }
}
}
Then in MyApp namespace you can use Country.ICountryInfo which is close to your requirement. Also using alias helps make the code clear.
This will work just fine, no need to nest:
public interface ICountry
{
ICountryInfo Info { get; }
}
public interface ICountryInfo
{
int Population { get; }
string Note { get; }
}
If ICountryInfo has no reason to exist outside ICountry, then why shouldn't you just put the properties of ICountryInfo in ICountry and dismiss the idea of nested interfaces?
An interface that hasn't a meaning of its own without another interface doesn't make sense to me, as an interface on itself is useless if not implemented by a class.

c# Class Design with Generics

How can i make the following class as general as possible (for maximum reuse) without creating too many classes of the same type, albeit with one extra property.
I want to avoid writing 3 slightly different versions of the same class
1# Class with No SubContent
public class Content
{
public string PageName { get; set; }
}
2# Class with Subcontent
public class Content
{
public string PageName { get; set; }
public IList<Content> SubContent {get; set;} //same as class
}
3# Class with sub content of another type
public class Content
{
public string PageName { get; set; }
public IList<DetailContent> SubContent {get; set;} //Note the different def
}
Of course i can create a generic class, but i find this confusing for consumers. It is inferring that the class is of Type T, when in fact its the Property that requires the type
public class Content<T>
{
public string PageName { get; set; }
public IList<T> SubContent {get; set;} //Note the different def
}
Generic Properties are not supported. So are there any patterns or suggestion on how i can handle this problem?
Perhaps you can have a look at the Composite Design Pattern
whats wrong with:
public class Content<T>
{
public string PageName { get; set; }
public IList<T> SubContent { get; set; } //Note the different def
}
?
it works you know...
What about
public class Content
{
public string PageName { get; set; }
}
public class ContentWithSubContent<T> : Content
{
public IList<T> SubContent { get; set; }
}
and if you want to be able to access SubContent not knowing the actual type, you could use
public class Content
{
public string PageName { get; set; }
}
public interface IContentWithSubContent
{
IEnumerable SubContent { get; }
}
public class ContentWithSubContent<T> : Content, IContentWithSubContent
{
public IList<T> SubContent { get; set; }
IEnumerable IContentWithSubContent SubContent
{
get { return this.SubContent; }
}
}
that way you can access the SubContent property bypassing generics if you need to, by using IContentsWithSubContent rather than Content.
Why not make an interface for the content classes:
public interface IContent {
public function GetContent()
}
and then you can use
List<IContent> in your content class?
you could even make the interface generic

Categories

Resources