How to instatiate a derived class instead of its base - c#

This is my problem:
I have a Class A that is used (instantiated) several times within a Class B.
I need to change the behaviour of the Class A, mainly the constructor, and then I derived it with Class C.
Class C: Class A
I would like that Class B using in its methods Class C instead of Class A, avoiding to override all the methods that used it.
Is it this possible?
Many thanks
I was not clear, therefore let me try to explain better with code.
Public Class A
{
`// Simple constructor
public A(params[])
{
// things here
}
}
Public Class C : A
{
// Constructor doing different thing then base
public C(params[]): base(params[])
{
// do different things here
}
}
Public class B
{
public B(params[])
{ }
public method_A(params[])
{
A _temp = new A(params[]);
// do things here with A
}
}
I use B in my program, but I would like that for one istance of B it uses A and for another instance of B it uses C instead of A.
Something like:
Main()
{
B _instance1 = new B();
B _instance2 = new B();
// use instance 1
_instance1.method_A(...);
// use instance 2
_instance2.method_A(...); // do something here for using C instead of A in the method
}

Just instantiate class C in class B and use it as you would class A, it will have the same functions as A with your added logic in class C.
in your constructor it might be worthwhile to do something like:
public class C : A
{
public C() : base()
{
// do stuff
}
}
so that it will also call A's constructor.

Related

Need to add same properties in two different classes

I have two classes like Class A and Class B. Class A have some properties, methods and Class B have only the properties. But both Classes have the same set of properties.
My Question is, If I add any new property in Class A, I need to add that in Class B also. If I did not add means, need to show error. How can I achieve this through C#?
You may achieve this by using an Interface and implementing it both in class A and class B. In the interface, define the property that is required in class A and B:
public interface ICommonProperty
{
string MyProperty{ get; set; }
}
Or you can use keyword abstract to create a class in common for A and B.
abstract class BaseClass // Abstract class
{
public int X {get;set;} // property in common for 2 class
}
class A : BaseClass
{
}
class B : BaseClass
{
public int Y {get;set;} // other property of B
}
You can go with the abstract class. The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.
Here is a simple example related to your question However you can understand and learn about Abstract classes here : Abstract Class
using System;
public class Program
{
public static void Main()
{
A objA = new A();
objA.printA();
B objB = new B();
objB.printB();
}
}
abstract class Parent{
public int a = 5;
}
class A : Parent
{
public void printA()
{
Console.WriteLine("In class A, value is "+a);
}
}
class B : Parent
{
public void printB()
{
Console.WriteLine("In class B, value is "+a);
}
}
Output of the above program is:
In class A, vlaue is 5
In class B, vlaue is 5
Hope this helps you.

Can you attach an interface to a defined class

Here is the situation. In some cases I find myself wanting a class, let's call it class C that has the same functionalities as class A, but with the addition that it has interface B implemented. For now I do it like this:
class C : A,B
{
//code that implements interface B, and nothing else
}
The problem will come if class A happens to be sealed. Is there a way I can make class A implement interface B without having to define class C (with extension methods or something)
Basically: no. That is part of what "mixins" could bring to the table, but the C# languauge doesn't currently support that (it has been discussed a few times, IIRC).
You will have to use your current approach, or (more commonly) just a pass-through decorator that encapsulates A rather than inheriting A.
class C : IB
{
private readonly A a;
public C(A a) {
if(a == null) throw new ArgumentNullException("a");
this.a = a;
}
// methods of IB:
public int Foo() { return a.SomeMethod(); }
void IB.Bar() { a.SomeOtherMethod(); }
}
The only way I see, is to change inheritance to aggregation, like this:
class C : B
{
public C(A instanceToWrap)
{
this.innerA = instanceToWrap;
}
//coda that implements B
private A innerA;
}
There seems to be a possibility to inject interface in run-time, as it is done with Array class and IEnumerable<T> interface, but it seems a bit of an overkill.
Is there a way I can make class A implement interface B without having to define class C (with extension methods or something)
The short answer is no. You can't make A implement B because you don't have control of A. However, I think you're headed down the right road with extension methods. Consider this:
public static class AImplementsBExtensions
{
public static void Func1(this A o) { }
public static void Func2(this A o) { }
}
Now clearly I have no idea what methods exist on B, but this is how you can implement B on A when you can't inherit from it.
Bear in mind, this is not an implementation. If you add or remove methods from the interface you'll have to do that by hand here. But now you can do this:
var a = new A();
a.Func1();
You could try creating your class without the inheritance: class C : B and as a wrapper around A.
Additionally you can provide implicit conversion operators so that code like A obj = new C(new A()) would work similar to how a derived class would work.
class C : B
{
private A _inner;
public C(A inner)
{
this._inner = inner;
}
public A Inner { get { return this._inner; } }
public static implicit operator A(C obj)
{
return obj == null ? (A)null : obj._inner;
}
public static implicit operator C(A obj)
{
return new C(obj);
}
}

How To Access Class A Folder To Be Used In Another Class

I am using C#
Scenario: Same project
FolderA - ClassA
FolderB - ClassB
I have a method in ClassB that needs the methods from ClassA.
How can I do that?
The folder part does not matter, but one common way to expose methods to other classes is to make them public. You can either use static or instance methods.
Ex
public class A
{
public void SomeMethod(){}
public static void SomeStaticMethod(){}
}
public class B
{
public B()
{
A a = new A();
a.SomeMethod();
A.SomeStaticMethod();
}
}
Another alternative is to use inheritance and let class A inherit from class B
public class A : B
{
public A()
{
//you can now call the methods defined in B
base.SomeMethod();
}
}
Above is an example of how to do it.

Sending base class to a method which receives derived class - c#

I have a Base class and 2 derived classes. I have a variable of base class which can hold one of the derived classes. I want to send that variable to a method which receives derived classes.
What can I do to resolve this problem without explicit cast since I don't know what the variable holds?
code:
Class A{
virtual public void foo1() {/.../}
}
Class B : A{
override public void foo1() {/.../}
}
Class C : A{
override public void foo1() {/.../}
}
Class D{
public foo(B argB) {/.../}
public foo(C argC) {/.../}
// in main
D varD = new D();
A varA = new B();
varD.foo(varA); //--->> Problem here need explicit casting
A varC = new C();
varD.foo(varC); //--->> Problem here need explicit casting
I don't know what derived class I'm sending to varD.foo and I want different handling of different derived classes. What can I do?
This is not what polymorphism is about - you can not pass a base class where a specialized class is expected, even when explicitly casting. Polymorphism works the other way: You can pass a specialized class wherever the base class is expected.
What you should do is make D.foo expect A and you will automatically be fine. If you add any methods to B or C which have no base implementation in A, you need to pass B anyway and can not cast an A to B or D.
Just make foo an abstract instance method of A and override the implementation in B and C. You could even keep your class D and delegate the actual work to there but it depends if this is a good idea.
Here the code with delegation to D. Also note that I omitted the method foo1() in all classes.
public abstract class A
{
public abstract void foo(D d);
}
public sealed class B : A
{
public override void foo(D d)
{
d.foo(this);
}
}
public sealed class C : A
{
public override void foo(D d)
{
d.foo(this);
}
}
public sealed class D
{
public void foo(B b) { [...] }
public void foo(C c) { [...] }
}
Now you can use virtual method dispatching to call the correct method.
D d = new D();
A b = new B();
A c = new C();
b.foo(d); // Calls B.foo(D) and in turn D.foo(B).
c.foo(d); // Calls C.foo(D) and in turn D.foo(C).

How to get a reference to an instance of a derived class from within a base class

.Net 3.5, using C#
I have an instance of a class (A) that has been called via a virtual method from a derived class (B). Within the method (a method of class A) I have discovered the Type of class B that has made the call, and using reflection I have examined class B and discovered a property whose value I want to access.
Is there any way via reflection to get the instance reference to class B? The only object I have is my ‘this’ reference.
[ Edit ]
By way of explaining that I'm not totally nuts for needing to do this: My class is T4NmpBase (class A). I have no control over the class in which I am inheriting (TextTransformation) or the class that inherits from me (TextTemplating - class B). I would like to use the "Host" property if it exits but do not want to put any burden on the programmer who is writing the text templating code that generates the TextTransformation class.
//
// this is my class
//
public abstract partial class T4NmpBase : Microsoft.VisualStudio.TextTemplating.TextTransformation {
public override void Initialize()
{
//
// determine derived class info and get value of "Host" property if it exists
//
}
}
//
// this class is generated by T4 in a project that I have no control over
//
[System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "10.0.0.0")]
public partial class PPTest : T4_NMP_Base.T4NmpBase {
public virtual global::Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngineHost Host { ... }
public override void Initialize()
{
base.Initialize();
}
}
In your case (assuming I follow correctly) your this reference is really your class (B) type, so you can use that to get the value of the property. So, just to make sure I follow correctly, you've got something that looks like:
public class ClassA
{
public virtual void VirtualMethod()
{
// Do your property investigation here
}
}
public class ClassB: ClassA
{
public override void VirtualMethod()
{
// Code for ClassB
}
}
And you are invoking the virtual method using something like:
ClassA instance = new ClassB();
instance.VirtualMethod()
So if that is the case then you should be able to get the value of the property by:
PropertyInfo proeprtyOnClassB // Assume you got this already via reflection
object propertyValue = propertyOnClassB.GetGetMethod().Invoke(this,null);
This sounds like a real problem with your design.
Is it possible to take Class B's property in question and make it a virtual property of Class A? Then you can override it in B but still access B's property from A. For example:
class A
{
public virtual string P
{
get { return "A"; }
}
public A()
{
Console.WriteLine(this.P);
}
}
class B : A
{
public override string P
{
get { return "B"; }
}
public B() : base() { }
}
When using:
B b = new B(); // prints "B"
If I understand correctly, from class A you want to access the functionality of the current instance through its concrete type B. Unless the member is not accessible to A because it's non-public, defined in another assembly, etc you don't need reflection. The following will work if the code in class A can see the members of derived class B.
B thisAsB = this as B;
if (thisAsB != null) {
// ...
}
But it does call into question the design of the class because class A should not have to know anything about its subclasses.

Categories

Resources