Implementing interface correctly in C# BOL classes - c#

I've been searching for a bit and found similar things but nothing that quite answers my question. Here it is- I have two classes. A, B. I want class C to have all the properites of those two classes. This is in the Object Layer, c#.net.
Class A:
public class A
{
public string property1 { get; set; }
}
public class B
{
public string anotherproperty { get; set; }
}
public interface IB
{
B b { get; set; }
}
public class C : A, IB
{
//nothing here cause hopefully it inherits everything
}
I have no idea if my implementation is even close. I do get error message of "C does not implement interface member IB"
Anyone know how to do this?

I have two classes. A, B. I want class C to have all the properites of those two classes.
...then you will have to manually add either A's or B's properties to C. C# does not support multiple inheritance, sorry.
However, in most cases multiple inheritance is not needed. A common alternative is to use composition instead of inheritance: For example, you could have your class C provide references to instances of A and B:
public class C
{
private A a = new A();
private B b = new B();
public A A { get { return a; } }
public B B { get { return b; } }
}
This would allow you to access all properties via myC.A.property1 and myC.B.anotherproperty.
If you really need to combine implementations from both A and B in C, you might need to have a look at Mixin libraries for C#.

You can do something like this:
public class ClassA
{
public string AProp { get { return "AProp";} }
}
public class ClassB : ClassA
{
public string BProp { get { return "BProp"; } }
}
public class ClassC : ClassB
{
}
And then:
ClassC c = new ClassC();
Console.WriteLine(c.AProp);
Console.WriteLine(c.BProp);
Prints:
AProp
BProp
You can't override anything but you can access the inherited properties.

Related

How to Pass objects between classes

So what I'm trying to do here is pass the same copy of a class (class A) to another class (class B), but class B is instanced in class A.
Using a new statement in class B won't work because it would cause an infinite loop, as well as creating a new instance of it, when I want to be able to use variables from the 1st instance of class A.
I know about object.equals() but I can't use it until I define the class A's object in class B. Just using object.equals results in a null reference.
public partial class class_A : Form
{
public class_B _class_B = new class_B;
public Int32 var;
private void setclassA()
{
_class_B._class_A.equals(this);
}
}
public class class_B
{
public class_A _class_A; // I know this is null
// code
}
Like I said I want to avoid instancing a new copy of class A because I want the values in class A to be set.
I've tried using a method to do it but still get a null reference.
Pass A in the constructor of B:
public class A
{
private B _b;
public A()
{
_b = new B(this);
}
}
public class B
{
private A _a;
public B(A a)
{
_a = a;
}
}
As mentioned in the comments you're completely misunderstanding .Equals(). It's used to compare whether two objects are equal not clone / pass references.
Answer
You're 75% there. As Ron mentioned, just change .equals(this) to = this as follows:
_class_B._class_A = this;
Explanation
If we want to pass the same copy of ClassA to ClassB, and to do that when we instantiate ClassB inside of ClassA, then we use the this keyword, which represents the current instance of a class.
Though there are other ways to give this to ClassB, the below example shows two:
pass this to the constructor and do the property assignment in ClassB or
assign this directly to a property in ClassB.
The key for you is that = is an assignment operator whereas Equals() checks whether two variables refer to the same object or not.
Example
public class ClassA
{
public ClassB MyClassB1 { get; set; }
public ClassB MyClassB2 { get; set; }
public ClassA()
{
// pass `this` to the constructor
this.MyClassB1 = new ClassB(this);
// pass `this` directly to a property in `ClassB`
this.MyClassB2 = new ClassB();
this.MyClassB2.MyClassA = this;
}
}
public class ClassB
{
public ClassA MyClassA { get; set; }
public ClassB() { }
public ClassB(ClassA classA)
{
// do property assignment in the constructor
this.MyClassA = classA;
}
}
Proof of Concept
This runs as a Fiddle here and prints out "They are the same object," and some other things too in the more recent version.
using System;
public class Program
{
public static void Main()
{
var classA = new ClassA();
if(classA.Equals(classA.MyClassB1.MyClassA) &&
classA.Equals(classA.MyClassB2.MyClassA) &&
classA.MyClassB1.MyClassA.Equals(classA.MyClassB2.MyClassA))
{
Console.WriteLine("They are the same object.");
}
}
}
An important note is that, when we use this, we're giving ClassB a reference to ClassA not a copy of it. These are very different things.
Try this:
public class A
{
public B Instance_B;
public A(B b)
{
Instance_B = b;
}
}
public class B
{
public A Instance_A;
public B()
{
Instance_A = new A(this);
}
}
Use get; set;
In Class A:
public partial class class_A : Form
{
Class_B B = new Class_B();
B.Class_A = this;
public Int32 var;
}
Then in Class B:
public class class_B
{
Class_A A { get; set; }
// code
}

Generic Methods passing subClass to baseClass defined Method?

QUESTION IS CLARIFIED
new thread : subclass properties accessed in generic method with superclass input
I have a base class A
subClasses B, C, and D inherit from A.
Each subClass has 3 subClasses a, b, and c.
a, b, and c have a list of unique properties.
However, now I want to build a generic function to access those properties, so how would I do this without switching on Type?
Clarification : I do not want a : B to have abstract C methods/properties
Example:
public void Method(A a){
if(a.isSubClassOf(B))
{Console.WriteLine(a.BaProperty);}
if(a.isSubClassOf(C))
{Console.WriteLine(a.CbProperty);}
if(a.isSubClassOf(D))
{Console.WriteLine(a.DcProperty);}
}
You can't define a member in derived class and access it via the reference to base class without casting to derived class:
class A {}
class B
{
public int i;
}
A a = new B();
a.i = 0; // error
((B)a).i = 0; // OK
Either declare virtual property in any of base types in your hierarchy, or use casting to the concrete derived type. Of course, in the second case your method doesn't make any sense.
Typically, you would use a virtual or abstract method defined in A and overridden in the subclasses.
public abstract class A
{
protected abstract PropertyType PropertyValue {get;}
public void Method()
{
Console.WriteLine(PropertyValue);
}
}
public class B : A
{
protected override PropertyType Property { get { return PropertyType.B; } }
}
// etc...
An elegant solution is to override ToString
public abstract class A { }
public class B : A {
public int b { get; set; }
public override string ToString()
{
return b.ToString();
}
}
// Do the same with C and D ....
A[] array = new A[] { new B(), new C(), new D() };
foreach (A a in array) {
Console.WriteLine(a);
}
Note that Console.WriteLine does not need to know about a special method or property in A. It also works for types not deriving from A.
It depends greatly in what you really want to achieve. In some cases what Steve Czetty suggests is the best option.
In others you could just keep all the properties different and have a virtual method in the base class that returns for example in this case a "string" that you can then write in the console or anything you wish.
Edit: You could override ToString as Olivier suggested. But only if you feel what yo are going to retun is the "String representation of the object".
public abstract class A
{
public string PropertyA { get; set; }
public virtual string GetString() //
{
return PropertyA;
}
}
public class B:A
{
public string PropertyB { get; set; }
public override string GetString()
{
return PropertyB;
}
}
public class C:A
{
public string PropertyC { get; set; }
public override string GetString()
{
return string.Format("{0} - {1}", base.GetString(), PropertyC) // for example if you wanted to do something more complex
}
}
Now if what you need can not be solved like this, you could cast as Dennis Suggested.
There is another posibility: you could use the visitor pattern. Here you can find several ways to implement it.
Just so you have an idea you would wind up having a class similar to this: (it will depend on what you really want to achieve)
You have to implement some other basic things (interface and some methods), but from a Reference to the base class you will be able to call the corresponding "Visit" method easily. There is a lot of detail in the link i added.
class ClassicVisitor : IAVisitor
{
public string SuperComplexStringResult { get;set; }
public void Visit(B b) { SuperComplexStringResult = String.Format("Super Complex Stuff + {0}", b.PropertyB); }
public void Visit(C c) { SuperComplexStringResult = String.Format("Super Complex Stuff + {0}", c.PropertyC); }
}

Dynamically Compose a Class in C#

Is it possible to dynamically compose a class from the methods contained in other Classes?
For instance. Class A, B and C have public methods named such that they can be identified easily. They need to be extracted and added to Class D. Class D, which then contains all of the implementation logic can be passed further into a system which only accepts a single instance of Class D and dynamically binds these methods to other functions.
To be clear, this is not inheritance I'm looking for. I'm literally stating that methods with different names need to be stuffed into one class. The system I pass it into understands these naming conventions and dynamically binds them (it's a black box to me).
I am going down the path of extracting the methods from A, B, and C, dynamically combining them with the source of Class D in memory and compiling them into a new Class D and then creating an instance of D and passing it forward.
public class A{ public void EXPORT_A_DoSomething(){} }
public class B{ public void EXPORT_B_DoSomethingElse(){}}
public class C{ public void EXPORT_C_DoAnything(){}}
//should become
public class D{
public void EXPORT_A_DoSomething(){}
public void EXPORT_B_DoSomethingElse(){}
public void EXPORT_C_DoAnything(){}
}
Is there a way to extract the MethodInfos from class A, B and C and somehow directly attach them to Class D? If so how?
I would consider using the C# Class compiler. From what I can remember you can build code that is in a string and you can get an assembly as output. This then enables you to invoke methods through reflection.
There is an example on the MSDN link I have specified but I will mock one up for here once I find my project.
You won't be able to export just the methods. The methods can't really be separated from the class that they are in. (they need access to all of the member fields/properites including inherited).
I think the only thing you can do is emit a interface implementation. (even though you say it's not what you need, I don't see a way around needing the private state for those objects)
You can make a single interface which contains only the methods you need, and provide a class that supports it which contains an instance of each type of object.
public class A{ public void DoSomething(){} }
public class B{ public void DoSomethingElse(){}}
public class C{ public void DoAnything(){}}
public interface ID
{
void A_DoSomething();
void B_DoSomethingElse();
void C_DoAnything();
}
public class D : ID
{
private A a;
private B b;
private C c;
public D(A a,B b, C c) { this.a=a;this.b=b;this.c=c; }
public void A_DoSomething(){ a.DoSomething();}
public void B_DoSomethingElse(){ b.DoSomethingElse();}
public void C_DoAnything(){ c.DoSomething();
}
If you need to generate this dynamically, look into Reflection.Emit. It'll be some business about how you've got to create a new assembly, and then load it dynamically into the AppDomain. I'd try to avoid that if you can.
It should actually be possible using something called "Mixins" and proxy generators. Take a look at Castle.DynamicProxy's tutorial: Mixins
Another solution is to define the class get and set accessors for the function as an interface, and declare the functions you are interested in.
interface iA
{
public int a { get; set; }
}
interface iB
{
public int b { get; set; }
}
interface iAB : iA, iB
{
}
class MyClass : iA, iB
{
public int b { get; set; }
public int a { get; set; }
}
static class MyClassExtender
{
static public int Foo(this iAB ab)
{
int c = ab.a + ab.b;
ab.a = c;
return c;
}
static public int FooA(this iA a)
{
int c = ab.a + 1;
ab.a = c;
return c;
}
static public int FooB(this iB b)
{
int c = ab.b + 1;
ab.a = c;
return c;
}
}
So now "MyClass" can use Foo, FooA, and FooB as public methods.
Have you considered simply using a hash or list of delegates in you D class that point to the methods on the other classes? Alternatively, use a dynamic object (google ExpandoObject).

Making a generic copy method with extensions

Context: this is for an engine, which is full of generic classes so that future users can extend certain parts of the behavior without concerning themselves with the inner workings of the engine itself.
Right now, I need a class C:
public class C
{
public C Copy(params) { ... }
}
But also an extension class D:
public class D : C
{
public D Copy(params) { ... }
}
Basically I have some generic classes, but I need a copy method (actually it's a "make a copy at a new location" method, but that's immaterial) which returns the right type.
public class SampleClass<T>
where T : C
{
public void Stuff()
{
...
T copy = favoriteThing.Copy(params);
...
}
}
and etc. I could just cast it, and trust future implementers to get it right, but I'd rather make it all explicit with contracts. Are there any elegant ways to do this?
One way might be to define an ICopyable<T> interface that's implemented by C and D:
public interface ICopyable<T>
{
T Copy(params);
}
public class C : ICopyable<C> { ... }
public class D : C, ICopyable<D> { ... }
Now if SampleClass<T> constrains T to ICopyable<T>, it can call Copy and get back an object of type T without any casts:
public class SampleClass<T>
where T : C, ICopyable<T> // added constraint
{
public void Stuff()
{
T favoriteThing = ...
...
ICopyable<T> copyable = favoriteThing;
T copy = copyable.Copy(params); // no cast needed
...
}
}

Can an upcasted object be downcasted again without trying a cast for every derived class type of the base class type?

I have case where am given a collection of objects that all derive from the same base class. If I iterate over the collection and check each item's type, I can see that the object is of a derived type and then handle it accordingly. What I would like to know is if there is an easier way of performing the check for the derived type besides what I am already doing. Code repetition typically isn't required, so my current methodology seems a bit off to me.
class A {}
class B : A {}
class C : A {}
class D : C {}
class Foo
{
public List<A> Collection { get; set; }
}
class Bar
{
void Iterate()
{
Foo f = new Foo();
foreach(A item in f.Collection)
{
DoSomething(a);
}
}
void DoSomething(A a)
{
...
B b = a as B;
if(b != null)
{
DoSomething(b);
return;
}
C c = a as C;
if(c != null)
{
DoSomething(c);
return;
}
D d = a as D;
if(d != null)
{
DoSomething(d);
return;
}
};
void DoSomething(B a){};
void DoSomething(C a){};
void DoSomething(D a){};
}
I am working with a web service where every web service must have the same result type.
class WebServiceResult
{
public bool Success { get; set; }
public List<Message> Messages { get; set; }
}
class Message
{
public MessageType Severity { get; set; } // Info, Warning, Error
public string Value { get; set; } //
}
class InvalidAuthorization: Message
{
// Severity = MessageType.Error
// Value = "Incorrect username." or "Incorrect password", etc.
}
class InvalidParameter: Message
{
// ...
}
class ParameterRequired: InvalidParameter
{
// Severity = MessageType.Error
// Value = "Parameter required.", etc.
public string ParameterName { get; set; } //
}
class CreatePerson: Message
{
// Severity = MessageType.Info
// Value = null
public int PersonIdentifier { get; set; } // The id of the newly created person
}
The goal is that we can return as many different types of messages back to the client as we want. Instead of getting a single message per web service call, the callee can know about all of their mistakes/successes in a single trip and to eliminate string parsing specific information from the message.
I originally though about using generics, but since the web service could have varying message types, the collection was broadened to use the base message class.
It may be possible to move DoSomething to A and have each subclass provide their own implementation:
public abstract class A
{
abstract void DoSomething();
}
void Iterate()
{
Foo f = new Foo();
foreach(A item in f.Collection)
{
item.DoSomething();
}
}
An idea would be to use a generic constraint on your base class or an interface.
public class MyClass<T> where T : BaseClass, IInterface
{
public void executeCode<T>(T param) {};
}
So MyClass<T> takes only a certain type, executeCode will have an idea what methods are exposed and what operations can be performed on the data of the object passed.
This avoids the need to cast because you are specifying a contract that must be followed.
typeof(ParentClass).IsAssignableFrom(typeof(ChildClass));
Return true is the cast is possible.
Also possible this way:
typeof(ParentClass).IsAssignableFrom(myObject.GetType());
But in your example, you actually call a methods for each object type. So you would need the cast anyway, unless you don't mind refactoring to not have a collection of overload.
Something like this if you want to keep the overload:
foreach(A item in f.Collection)
{
Type itemType = item.GetType();
if (typeof(B).IsAssignableFrom(itemType)
DoSomethingB(item);
else if (typeof(C).IsAssignableFrom(itemType)
DoSomethingC(item);
//...
}
EDIT: I like more Lee's answer. Adding virtual/override function to the class type would be a better design and way easier to handle, unless the DoSomething really has nothing to do being in the classes.
Lee is right. Just let the item decide, what to do. It knows it's type best and therefore knows what to do. You might even give some standard implementation, if it is the same as in A, by not making it abstract, but virtual. Be aware though, that the compiler wont ask for an implementation then.
public class A
{
public virtual DoSomething(){"What A needs doning!"}
}
public class B : A
{
public override DoSomething() {"What B needs doing!"}
}
Another way would be the use of Interfaces.
public interface IAinterface
{
void DoSomething();
}
public class A : IAinterface
{
void DoSomething(){...}
}
public class B : IAinterface
{
void DoSomething(){...}
}
This would be more like Lees suggestion, although interfaces and abstract base classes work a bit different in the background.
I usually prefer the upper one, because I usually tend to give the base class some standard behavior and only implement derived classes, when there is something different.

Categories

Resources