How to create a classes that inherit any class at runtime - c#

I am guessing this isn't possible since c# doesn't support prototyping but worth an ask.
I have a big set of unrelated classes, all inheritable, let's take two of them: Bar and Baz.
I want to extend all these classes in the same way: adding two public int properties: X and Y, and potentially some other private variables and methods down the road. Let's call this class (before inheriting) Foo, and Foo is meant to inherit Baz, Bar and so on.
I don't want to have to explicitly create different classes for Bar, Baz, ....
class FooBaz : Baz
class FooBar : Bar
...
Instead, Is there a way I can create a kind of factory that takes the classes, e.g bar, baz and then returns an object of the that is foo : bar, or foo : baz etc?
Var FooedBaz = New Foo(Baz);
WriteLine(FooedBaz.X);
Why do I want this?
Because I am using WPF and extending various UIElements like Image to add x and y coordinates onto them. This way I can directly use the classes within the WPF system without have to access members etc.

If having "real" inheritance is not a mandatory requirement, I would go with ICustomTypeDescriptor, or with CustomTypeDescriptor which has most of the boilerplate pre-implemented, if you do not have change it. Thus it will be working effortlessly with all of the .NET Type APIs. The implementation can receive an instance of an arbitrary type, decorate it with the additional logic, and then route this logic through the ICustomTypeDescriptor API. Here is a very dummy pseudo implementation.
private class DynamicType<T> : UIElement, ICustomTypeDescriptor where T : UIElement
{
public DynamicType(T wrapped)
{
. . .
}
public int CustomProp1 { get; set; }
public int CustomProp2 { get; set; }
public override PropertyDescriptorCollection GetProperties()
{
var prop1AndProp2 = base.GetProperties();
var wrappedProps = TypeDescriptor.GetProperties(wrapped);
return prop1AndProp2 + wrappedProps;
}
. . . other ICTD methods . . .
}

Related

Using new keyword in interfaces for methods with different return types to wrap/unwrap data

Consider the following interface and class setup setup
class A {
public string SomeData {get;set;}
}
class B {
public string Test{get;set;}
public int Other{get;set;}
public decimal Stuff{get;set;}
}
interface Foo {
A GetA();
B GetB();
}
interface Bar : Foo {
new string GetB();
}
class BarImplementer : Bar {
private readonly Foo _foo;
A GetA(){
// Check cache for existance of A, otherwise use _foo to get A...
}
string GetB(){
// Check cache for existance of B, otherwise use _foo to get B...
return b.Test;
}
// This is forced upon me by the compiler because otherwise this class "does not implement all methods of interface 'Bar'"
B Foo.GetB(){}
}
Ideally, users of the BarImplementer class should not need to deal with the B class as they're only interested in the Test property of a B object.
As you can see from the comments, this won't compile without adding a B Foo.GetB implementation with no access modifier. I'm struggling to find examples of the new keyword being used to hide methods like this structure in interfaces online.
My question is, what's the most correct way to go about achieving this or equivalent result. Is it better to subclass an implementation of Foo in some way to implement the equivalent of Bar rather than a Bar interface inherit from Foo and then implement Bar and Foo separately.
If it helps, in the reality of this simplified setup (in a Dependency Injection environment), an implementation of Foo is used to get data from HTTP calls, and an implementation of Bar can cache the result of those calls to avoid making them multiple times.
It's not 100% clear to me what all you are trying to accomplish, but I believe your primary issue is the name GetPropertyOfB. Because the name differs from Foo's GetB, it isn't hiding it like you expect. Try changing
interface Bar : Foo {
new string GetPropertyOfB();
}
to:
interface Bar : Foo {
new string GetB();
}

Properties in an Interface

In my interface, I have declared a property with setter and getter.
public interface ITestInterface
{
string AProperty { get; set; }
}
When I code my class which inherit that interface, why I need to define these two properties again?
public sealed class MyClass: ITestInterface
{
public string AProperty { get; set; }
}
Because you are not inheriting from an interface, you are implementing the interface. (although they both share same syntax :)
public class MyClass : IMyInterface { ... } //interface implementing
public class MyClass : MyBaseClass { ... } //inheriting from a class
Assume you are inheriting a candy box (not from your ancestors, in programming manner), it is something (not exactly) like you put the candy box in another box, now the outer box (the derived class, the inherited one) is inherited from candy box and have all the things candy box have, but if you want to implement (make) a candy box yourself you must build a box and put some candy in it. This is the way interfaces work.
Your interface definition only tells there is a property with a getter and setter, not how it is implemented. You could use auto-implemented properties, but you are not required to.
Following the interface, this would be a valid implementation:
public sealed class MyClass: ITestInterface
{
public string APROPERTY
{
get { return someField + " hello"; }
set { someOtherField = value; }
}
}
In an interface definition, string AProperty { get; set; } is the declaration of the property, while in a class, it means that the property is auto-implemented.
Short answer
Because interfaces contain no more than a definition of a class, and cannot contain the actual implementation of any member functions. It's by design.
Long answer
First you have to realize that properties are basically get and set member functions with some simplified syntax. The question here is therefore: why can't an interface definition contain an implementation of a member function?
Well, in some languages (most notably: C++) you can.
If you have an inheritance chain, that's basically solved through lookup tables. Say that you have member function 1, then in all the classes in the inheritance chain, there's a table which contains a pointer to function 1. Once you call a member function, the call basically grabs the first entry from the table belonging to the type of your object, and calls that. This thing is called a vtable (and for more details, see here).
Now, in C++, VTables are very transparent to the developer: each class basically has a vtable and there's no such thing as a real 'interface'. This also means that all classes can have implementations and members such as fields. If you have a class with only pure virtual members (e.g. functions without an implementation), you have the C++ equivalent of an 'interface'.
In software engineering, these classes were often called 'interface' classes, because they contain only a definition of what's going on, not the actual implementation. Interfaces have the nice property that they describe functionality without actually going into the details, thereby giving the possibility to put 'boundaries' in your code. There are a lot of use cases for this, including (RPC) communication, a lot of design patterns, and so on.
In C++, a class can derive from multiple classes (multiple inheritance) with and without an implementation. Also, because interfaces are in fact more like 'abstract' classes than like 'interfaces' in C#, this means you can also add functionality there. The vtable that was previously described therefore contains pointers to functions in all the base classes.
The problems with this start when you're starting to add functionality to interface classes. For starters, let's say you have something like this (I'll do this in sort-of C#):
interface A { Foo(); } // basically an interface.
interface B : A { Foo(); } // another interface
class B : A { void Foo() {...} } // implementation of Foo, inherits A
class D : B,C { } // inherits both B, C (and A via both B and C).
What we're interested in here is what happens if you call Foo in class D. For that, we have to construct a vtable for class D. Basically this vtable would look like this:
Foo() -> C::Foo()
This means that if you construct an object of D, and call Foo, you'll end up calling the implementation of Foo in type C:
var tmp = new D();
tmp.Foo(); // calls C::Foo()
It becomes more difficult when we're changing the definition of B into something like this:
class B : A { void Foo() {...} } // changed into an implementation
Again, we try to construct the vtable for class D and we end up with a problem:
Foo() -> C::Foo() or B::Foo()???
The problem we're facing here is: what implementation of Foo are we going to use when calling that member? Also, what constructor are we going to call? And what about destruction order? In C++ there are workarounds for this called virtual inheritance.
While designing .NET and the C# language, they thought about past experiences with multiple inheritance and the implications of virtual inheritance and decided that it's not only a difficult thing to implement, but also very confusing for developers at best. As you've seen, these problems don't exist when you just add interfaces.
So, that's why you cannot have a property (or a method) in your interface.
I think the problem here is, that the same syntax has two different meanings for interfaces and classes. AProperty { get; set; } is in an interface is the declaration-only, in a class it's an automatically implemented interface.
So that term is dependent on the context.
public interface ITestInterface
{
string AProperty { get; set; }
}
Declares the Property, but cannot implement it.
public sealed class MyClass: ITestInterface
{
public string AProperty { get; set; }
}
Implements the interface, where the property is automatically implemented (which only works for classes).
Interface contain property signatures not the actual definitions. You are actually requesting for any class implementing ITestInterface to implement get and set for AProperty. See this and this for more details.
As others say interface is just a container for your methods and properties signatures. It needs implementation but this implementation signature will be perfectly match with one that is used in interface. Also it guarantees that all of this members can be accessed in a class instance as they are by default public properties and without implementation program will not compile at all.
Let's say you have interface:
public interface ITestInterface
{
string AProperty { get; }
}
and class that implements it:
class MyClass : ITestInterface
{
public string AProperty { get { if (DateTime.Today.Day > 7) return "First week of month has past"; return "First week of month is on"; } }
}
It's not possible to use auto-implemented properties and not possible to add setter in this class because interface property lacks set accessor and auto-implemented properties requires that interface contains auto-implemented properties signature ({ get; set;}). So in your example interface just declares properties and that's it.
Just by knowing what interfaces class has inherited you know what members are there and if you just want to use (or allow user to use) some of this methods (not allowing to change anything though) you can always upcast your class instance to one of these interface types and pass it as a parameter.
I think the confusion here comes from the fact that auto properties (just the get and or set declarations) look the same in the interface and the implementation. The interface is merely a declaration (contract) of what a class must provide in order to be deemed an implementer of the interface. It is much clearer if you consider a method declaration in an interface vs its implementation in a class.
Interface = requirements;
Class = how those requirements are fulfilled
public interface ITestInterface
{
string GetAProperty();
}
public class MyClass : ITestInterface
{
public string GetAProperty()
{
// Do work...
return "Value";
}
}

When should I use inheritance over utility classes?

I am working on a project that uses Canvas objects. I would like to add a few functionalities to manipulate them.
Until now, I was adding them in a CanvasUtils class but now I realize that I could actually create a CustomCanvas class that would inherit from Canvas and implement the new functionalities.
I can feel the second way is more intuitive but I am not sure whether it is the best option or not.
For example, if I keep adding new methods to a CustomCanvas class it is going to become huge at some point whereas I can easily break a utils class into several ones.
Also a Utils class sounds more independent and extendable to me. For example, if I wanted to extend some of the functionalities to Panel objects (Canvas inherits from Panel), I think it would be easier to do it with a Utils class as you just have to change the Canvas references to Panel.
My questions are:
what are the advantages and flaws of each method and
when should I use one over another?
If you are adding new functionality, then you should extend the class. You'll be able to add your own state, as well as methods to interact with them. However, you won't be able to add this functionality to existing objects.
If you are simply writing shortcuts that use existing functionality, then you can use Extension Methods to add functions without needing to extend the class. For example...
public static class PanelExtensions
{
public static void DoSomething(this Panel panel)
{
panel.SomePanelMethod();
panel.SomeOtherPanelMethod();
}
}
And then to use this...
Panel myPanel = new Panel();
myPanel.DoSomething();
The advantage of this approach is that the methods are available to existing panels, and they will be inherited too (so your Canvas objects will receive these methods too).
Note than in order to use extension methods, you need to have a using statement at the top of your file referencing the namespace in which they are defined.
It depends on what you are trying to achieve and what do you need to implement new functionality:
If you have stateless methods that do not need any additional information associated with object, then you can either continue to use Util methods or turn them into Extension methods that will give you both the inheritance-like feel of use and loose coupling of the Util class:
public static class CanvasExtensions
{
public static void TransformElements(this Canvas canvas,
Action<CanvasElement> transform)
{
...
foreach(var elem in canvas.Children)
{
transform(elem);
}
...
}
}
If you need to associate some piece of info with the object you operate on, then:
you can either inherit the class if the object's behaviour shall be deeply affected by additional functionality (like when other standard methods can negate new functionality) to allow base function overriding:
public class DeeplyAffectedCanvas : Canvas
{
private IDictionary<CanvasElement, Action> m_dictionary;
public void SpecialTransform(CanvasElement elem, Action transform) { }
public override void Resize()
{
// Resize, for example, have to take into account
// the special operation
}
}
or create a wrapper, that exposes the original object (Panel) when the additional behaviour doesn't affect the wrapped object much:
public class Wrapper<T>
{
public Wrapper(T wrapped)
{
this.Wrapped = wrapped;
}
public T Wrapped { get; private set; }
public implicit operator T (Wrapper<T> wrapper)
{
return wrapper.Wrapped;
}
}
public class WrappedCanvas : Wrapper<Canvas>
{
private Object data;
public void SafeTransform(...);
}

To abstract, or not to abstract

thanks in advance for reading this. I don’t fully understand how/when to use abstracts so I am trying to think about it each project I work on to see if it will all click some day Smile | :)
Also, the mix of accessibility levels (private, protected, internal) with keywords static, abstract, and override tend to leave me a little confused. How do I define this method/property/class....
It's not all a big mystery to me but some projects have me coding in circles when dealing with these topics.
With that said,
I have an application that reads an XML document and outputs text and image files. I’m also storing all of the information in a database. I have it working nicely.
The XML has a standard implementation with required fields and is used by multiple organizations to submit data to my app. All organizations should use (at least) the required nodes/elements that are outlined in the XML implementation guide.
So, I want to have a default data object type to be able to derive a specific organization’s data type for required elements. (If this object is going to be used, these are the fields that must be implemented).
If the org. just uses the default requirements, I can use the default object. If they use additional (optional) fields, I’ll have to create a new type inheriting the default type.
My first thought was to use and abstract class that had protected properties for my bare minimum requirements:
public abstract partial class AbstractDataObject
{
protected string DataObjectName;
protected DateTime? DataObjectDate;
etc...
}
Then, if the organization just uses the required elements of the node and no optional elements, I can use a “default” object.
internal partial class DefaultDataObject : AbstractDataObject
{
public new string DataObjectName { get; set; }
public new DateTime? DataObjectDate { get; set; }
etc...
}
But, if an organization uses optional fields of the required node, I can use a derived organization data object.
internal sealed partial class OranizationDataObject : AbstractDataObject
{
public new string DataObjectName { get; set; }
public new DateTime? DataObjectDate { get; set; }
etc...
//Optional fields used by this organization
public string DataObjectCode { get; set; }
etc...
}
Do I need the abstract class? It seems to me I can just have a DefaultDataObject (something like):
internal partial class DefaultDataObject
{
public virtual string DataObjectName { get; set; }
public virtual DateTime? DataObjectDate { get; set; }
etc...
}
And then:
internal sealed partial class OranizationDataObject : DefaultDataObject
{
public override string DataObjectName { get; set; }
public override DateTime? DataObjectDate { get; set; }
etc...
//Optional fields used by this organization
public string DataObjectCode { get; set; }
etc...
}
I’m just really trying to understand how to define these objects so I can reuse them per organization. Both ways seem to work, but I am hoping to understand how to define them properly.
Getting the XML into above objects:
public DefaultDataObject ExtractXmlData(XContainer root)
{
var myObject = (from t in root.
Elements("ElementA").Elements("ElementB")
select new DefaultDataObject()
{
DataObjectName = (String)t.Element("ChildElement1"),
DataObjectDate =
Program.TryParseDateTime((String)
t.Elements("ChildElement2")
.ElementAtOrDefault(0)
),
etc....
OR
public OranizationDataObject ExtractXmlData(XContainer root)
{
var myObject = (from t in root.
Elements("ElementA").Elements("ElementB")
select new OranizationDataObject()
{
DataObjectName = (String)t.Element("ChildElement1"),
DataObjectDate = Program.TryParseDateTime(
(String)t.Elements("ChildElement2")
.ElementAtOrDefault(0)),
DataObjectCode = (String)t.Element("ChildElement3"),
etc....
Again, thanks for reading. Don't forget to tip your wait staff....
Joe
First of all, your base class doesn't need to be abstract if it's a plain DTO class. If you don't have any functionality that needs to be implemented differently by derived classes, you can simply make it a plain base class which will hold common properties.
Next, there is no point in declaring properties in the base class (abstract in your case), if you are going to hide them (using the new keyword). You first code snippet of DefaultDataObject unnecessarily creates a bunch of new properties with the same name. Remove them completely - they are already defined in the base class.
[Edit] I didn't notice this initially, and #svick warned me, that your base class actually contained fields instead of properties, which makes me wonder why you needed to add the new keyword at all. I went over your code quickly and saw them as properties. In any case, you should never expose public fields - at least change them to auto-implemented properties by adding the { get; set; } block.
In other words, this would simply work:
// this doesn't need to be abstract.
// just put all the common stuff inside.
public class BaseDO
{
// as svick pointed out, these should also be properties.
// you should *never* expose public fields in your classes.
public string Name { get; set; }
public DateTime? Date { get; set; }
}
// don't use the new keyword to hide stuff.
// in most cases, you won't need that's behavior
public class DerivedDO : BaseDO
{
// no need to repeat those properties from above,
// only add **different ones**
public string Code { get; set; }
}
As a side note, but nevertheless important IMHO, you should simplify naming (and make it more clearer what your code does). There is no need to repeat "DataObject" in every property name, for example. But since your code is probably only a simplified version, it doesn't matter.
Lastly, have you heard of XmlSerializer? You don't need to traverse the XML elements manually. It is enough to call XmlSerializer to both serialize and deserialize your data.
Everything I need to know I learned from Sesame Street
Scrub your class design hard to make sure you've identified everything that is the same and different. Play computer, so to speak, with your classes and see how they do the same, different, or the same thing but in different ways.
What is the same, different, same but differently will likely change as you play computer.
Think in general terms of the two pillars of OO Classes. Polymorphism and Inheritance
As you do the above that is. Not so much in terms of C# implementation per se.
How things clump into same vs. different will help drive implementation
And it's all relative.
More of same default behavior? Perhaps a concrete base class instead of abstract.
More of same thing, but differently? Perhaps an abstract class instead of concrete base class.
A default way of doing x? Perhaps a virtual method.
Everyone does the same thing, but no two the same way? A delegate perhaps.
Implementation Suggestions
Make methods and fields protected as a default. Private does not get inherited. Designs change, stay flexible. If something just has to be private, fine.
virtual means you can change implementation in a sub class. It does not mean you must.
Folks seem to under-utilize delegates. They're super for polymorphic methods.
There is nothing wrong with public fields. What's the practical difference between a public field and a public auto-implemented property? Nothing. They both directly return (or set) the underlying value. So what's the point of even bothering with properties? If you want to publicly expose an underlying value differently than it's "natural" state. For example, returning a number in a specific format. And of course you can have different properties for the same field.
A Property can have a get without a set. Or vice versa. Also get and set can have different access levels. Often you'll see this as a public get and a protected (or private) set.
It depends on what the derived types will want to do. If they are going to use the default implementation and only expand on it somehow, then having the default class as the non-abstract base class is fine.
On the other hand, if they are most likely going to re-implement the functionality, you should have an abstract base class (or an interface) and a separate default class.
If you for some reason don't know which one is it, you can let the inheritors choose by having an abstract base class and leaving the default class unsealed.
Also, looking at your code, it seems you misunderstand what the various keywords do. Most of the time, you do not want to use new like this. What it does is to define another member with the same name, unrelated to the original one. Also, there's no reason to override something if you don't want to change it. So, if you expect that the derived classes won't have to reimplement the properties, you don't have to make them virtual at all.
An abstract class can already implement things that can be inherited
public abstract class DataObjectBase
{
public string DataObjectName { get; set; }
public DateTime? DataObjectDate { get; set; }
}
A concrete class can add new properties and methods
public class DerivedDataObject : DataObjectBase
{
public int NewProperty { get; set; }
}
The properties DataObjectName and DataObjectDate are already available in the new class, because they are automatically inherited from the base class.
If the abstract class defined an abstract member, however, you would have to implement it in the derived class.
Say the base class defines
public abstract void SomeMethod(string name);
The the derived class has to do this
public override void SomeMethod(string name)
{
...
}
If your base class does not have abstract members, it does not need to be abstract and can play the role of your default data object directly.
The keyword 'partial` is not needed here. It is only useful if you want to split one class into several pieces over several files.
The keyword new is wrong here. It is used to shadow an inherited member. This means that the inherited member will be hidden "behind" the new declaration. What you need, is to override. This does not hide a member, but provide an alternative implementation of the same member in the derived class.

Creating which derived type of class at runtime

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.

Categories

Resources