How to identity which class object is being created in Helper class - c#

I am having a abstract class which is being inherited by 2 classes. How can I find out which class is being created in my helper class.
Abstract Class
public abstract class AbstractClass
{
private IHelper helper{ get; }
public Entity()
{
helper= new MyHelper(this);
}
}
MyHelper.cs
public class MyHelper: IHelper
{
private AbstractClass ABClass{get;}
public EntityDataOperation(AbstractClass abClass)
{
//How can I find out which concrete type it is i.e. ClassA or ClassB
ABClass= abClass;
}
}
ClassA
public class ClassA:AbstractClass
{
public string data= "ClassA";
}
ClassB
public class ClassB:AbstractClass
{
public string data= "ClassB";
}

You can use Reflection but your code and methodology is very questionable:
entity.GetType().Name;
You can also test for the subclasses
if (abClass is ClassA)
// found is ClassA
else if (abClass is ClassB)
// found ClassB

It seems like your question boils down to, "If I have an object, how do I get the type of that object?"
var typeOfTheObject = theObject.GetType();
The problem is that this largely defeats the purpose of strongly typed parameters.
This tells you what you need to know about the type:
public EntityDataOperation(AbstractClass abClass)
^^^
That tells you what the type is. It's AbstractClass. If that's not what you need to know - if you don't care that it's an AbstractClass, then why not change the parameter to object?
Polymorphism literally means "multiple shapes." It means that the when you get an instance of AbstractClass, the actual object could be one of many shapes - many implementations of the class. But by taking a parameter of type AbstractClass, this method says that it doesn't care which type it is. It just interacts with the interface it knows about - the methods and properties of AbstractClass, without knowing or caring what the concrete implementation is.

Related

How to reference abstract class

When posting this question my hope was to find a way how to reference/point to
an abstract class that that could be used by a worker/holder.
As the comments by #progman suggested and #laryx-decidua there is no way to hold a reference to an abstract class, but one can only hold a reference to a instantiated object.
Below you can find what I think is their proposed solution. To me this is an ugly solution, and I would have liked to have one that derives multiple static classes from an abstract base class and the holder gets references to those static classes to do its work. Deriving a static class form an abstract class Why you can't drive a static class is it seems prohibited by design and indicates bad architecture; although I don't see why the solution above is any better.
Suggested Solution
using System;
using System.Collections.Generic;
public abstract class BaseClass
{
// Some declarative knowledge
public int value;
protected BaseClass(int value){
this.value = value;
}
// Some procedural
public abstract void execute();
}
public class ConcreteClass1 : BaseClass
{
public ConcreteClass1() : base(42) {}
public override void execute()
{
Console.WriteLine("In Concrete1! Value " + value);
}
}
public class ConcreteClass2 : BaseClass
{
public ConcreteClass2() : base(8888) { }
public override void execute()
{
Console.WriteLine("In Concrete2! Value " + value);
}
}
public class Holder
{
BaseClass activeClass;
public void setClass(BaseClass newClass){
activeClass = newClass;
}
public void doWork()
{
int x;
activeClass.execute();
x = activeClass.value * activeClass.value;
Console.WriteLine("Holder has done its work: " + x);
}
}
class MainClass
{
static void Main(string[] args)
{
List<BaseClass> classes = new List<BaseClass>();
classes.Add(new ConcreteClass1());
classes.Add(new ConcreteClass2());
Holder holder = new Holder();
holder.setClass(classes[0]);
holder.doWork();
holder.setClass(classes[1]);
holder.doWork();
holder.setClass(classes[0]);
holder.doWork();
}
}
producing
In Concrete1! Value 42
Holder has done its work: 1764
In Concrete2! Value 8888
Holder has done its work: 78996544
In Concrete1! Value 42
Holder has done its work: 1764
Disclaimer: I don't speak C#, but I suspect the situation is similar to C++. The rest of the answer is based on my C++ and general OOP experience.
If I understood you correctly, you'd like to hold derived class object(s) through a base class reference and invoke a polymorphic ("virtual") method on those objects. Because you expect those derived classes to be "stateless" (i.e. no data members), you thought maybe you could "get away with" static (and/or abstract) classes.
The problem is that you need to instantiate something to put into your Holder objects, because a reference (or a pointer) can refer to (point to) only to a concrete object. So you need to instantiate objects that will be referred to via a reference in Holder, as some of the commenters have already pointed out. That's why abstract classes won't do -- they cannot be instantiated.
If there were an OOP language that supports references to types , plus some mechanism that can do the following: "Hmm, here is a reference AnimalTypeRef to the (possibly abstract) base class type Animal. AnimalTypeRef actually refers to the derived class type Elephant. Now, the user wants to invoke a virtual method Animal::make_noise() that does not use any class state, so let's invoke the corresponding method Elephant::make_noise() that overrides it and returns this :-)." -- well, then you could do what you have asked for.
I suspect this has not been implemented in C++ or C# because there are not too many use cases for it, and actually the same thing can be done with the general mechanism that requires that references refer to concrete objects.
Just go ahead and derive concrete (non-abstract) classes from your abstract base class, and don't worry about their statelessness. It's perfectly OK to define and use concrete objects that have no data members. Instantiate them, then initialise a Holder object with them, using a reference to the (abstract) base class and that's it. Polymorphic method invocation through base class references will do the rest.

Subclassing and generics in C#

I want to subclass a large number of classes so that they will all contain a certain set of the same properties. What would be the right way to do it in order to avoid repetition? I thought of using generics like:
public class SuperT<T> : T
{
//the same set of properties
}
But the compiler says
Cannot derive from 'T' because it is a type parameter
EDIT: I am trying to subclass some classes in a third party assembly so I cannot use a base class.
For example, the types are "Image", "Label", "Button" etc and I want to subclass them all to contain a property like "Radius". (So that I would use SuperImage element in XAML and when I set it's Radius property from XAML, I will be able to run some certain logic.)
One other way I just thought of right now is using T4 templates. I wonder if there is a way to do this with generics without resorting to templates? I cannot understand why the compiler rejects it.
If these classes all share a common base class or common interface you could write an extension method.
public static class ShapeExetnsionsExtLib
{
public static double Radius(this ShapeBase shape){
return /*calculate radious*/;
}
}
From comments
I am trying to subclass some classes in a third party assembly so I cannot use a base class.
For example, the the types are "Image", "Label", "Button" etc and I want to subclass them all to contain a property like "radius".
Yes they share common base classes but I cannot add anything new to them.
I don't think generics have anything to do with this, however inheritance is probably what you're looking for.
There are two types of inheritance that you can use to subclass, and extension methods work to "superclass"... sort of.
Is-A inheritance
Has-A inheritance
And to simply add a similar method to a bunch of third party objects, you'll use an extension method.
Is-A inheritance
Use a base class if you've got similar method implementations.
public abstract class BaseFoo {
public void Bar() {
// actual code
}
}
public class Foo : BaseFoo
{
}
var foo = new Foo();
foo.Bar();
Use an Interface if you need to implement the same method on each class.
public interface IFoo {
void Bar();
}
public class Foo : IFoo {
public override void Bar(){
// bar implementation
}
}
var foo = new Foo();
foo.Bar();
Combining the two is also allowed, but you can only inherit on base class, where you can inherit multiple interfaces.
Has-A inheritance
This is particularly useful with dependency injection, but it's simply the notion that you have an instance of another class to work with. It's essentially a wrapper class for you to work with.
public class Foo {
private readonly ThirdPartyFoo _tpFoo;
void Foo(ThirdPartyFoo tpFoo) {
_tpFoo = tpFoo;
}
public void Bar(){
// now I can do something with _tpFoo;
_tpFoo.Bar();
}
}
var tpFoo = new ThirdPartyFoo();
var foo = new Foo(tpFoo);
foo.Bar(); // invokes the underlying tpFoo
Lastly, if you just need to add a method to existing classes, then you create an extension method.
public static class ViewExtensions()
{
// this assumes your Image, Button, Label all inherit from View.
public static Whatever Radius(this View view) {
// do your radius work.
}
}
Just Use a base class:
public class Base
{
public int Id { get; set; }
public string Name { get; set; }
}
And inherite from it:
public class A : Base
{
}
public class B : Base
{
}
In general, you want to use one of the answers already posted about using a base class and inheriting from that. However, if the classes are in a third party library and are marked as sealed, then you will need to create a wrapper class to use as a base class.
(Note that this option is a workaround and doesn't truly inherit from the third party class, so things in that class that are marked as protected won't be accessible without a liberal use of reflection.)
// The sealed class within another library
public sealed ThirdPartyClass
{
public ThirdPartyClass(int i) { }
public int SomeProperty { get; set; }
public int SomeMethod(string val) { return 0; }
public static void SomeStaticMethod() { }
}
// The wrapper class to use as a pseudo base class for ThirdPartyClass
public class BaseClass
{
private ThirdPartyClass _obj;
public BaseClass(int i) { _obj = new ThirdPartyClass(i); }
public int SomeProperty
{
get { return _obj.SomeProperty; }
set { _obj.SomeProperty = value; }
}
public int SomeMethod(string val) { return _obj.SomeMethod(val); }
public static SomeStaticMethod() { ThirdPartyClass.SomeStaticMethod(); }
}
// The child class that inherits from the "base" BaseClass
public class ChildClass : BaseClass
{
}
First of all, this might be a logical problem. What if you are going to extend a sealed class? Or Int32 class? Delegate?
Anyway, the way I recommend is to create an interface and implement all the functions you need in the subclass.

Defining factory methods in interfaces or abstract superclasses of the product class

I have an abstract super class and subclasses inheriting from it.
Each subclass MySubclass shall have a public static MySubclass CreateFrom(ISomething something) factory method. The interface of its argument is the same for all subclasses, but the return type must of course always be the type of the respective subclass.
Can I somehow achieve this to have static factory methods following an interface or abstract superclass method definition without creating a separate static factory class for each single subclass?
If the ISomething is always of the same (or at least a common) type, you could make the CreateFrom method of the superclass generic and Invoke the constructor of the inherited class with the parameter. Just make sure all your inherited classes have that constructor (Not sure but I don't think there is a way to 'force' a constructor pattern).
public abstract class SuperClass
{
public static T CreateFrom(ISomething something)
{
return (T)Activator.CreateInstance(typeof(T), something);
}
}
public class InheritedClass : SuperClass
{
public InheritedClass(ISomething something)
{}
}
This way you can create instances by calling
SuperClass.CreateFrom<InheritedClass>(something);
Or you split the creation and initialization:
public abstract class SuperClass
{
protected abstract void Initialize(ISomething something);
public static T CreateFrom(ISomething something) where T : new()
{
T result = new T();
T.Initialize(something);
}
}
public class InheritedClass : SuperClass
{
public InheritedClass()
{}
protected override Initialize(ISomething something)
{}
}
You can´t define static members on interfaces as static members belong to a certain class. However I can´t imagine of a reason to use this. You should ask yourself why you need such a functionality. Does a sub-class really have to instantiate itself or can the same easily be done with another independent (factory-)class?
Just create one simple factory-class with a generic parameter that indicates what to create.
class Factory<T> where T: new()
{
T CreateFrom(ISomething param)
{
return new T();
}
}
Now you can simply call it like this:
var myFactory = new Factory<MyClass>();
myFactory.CreateFrom(mySomething);
I resorted to a different solution in similiar kind of requirement. In my superclass which happened to be an abstract one I required to create an instance of subclass to do something with it so I did the following trick:
public abstract class Element
{
protected virtual void copyFrom(Element other)
{
}
protected abstract Elememt newInstanceOfMyType();
public object clone()
{
var instance= newInstanceOfMyType();
instance.copyFrom(this);
return instance;
}
}
Now all my subclasses inheriting from Element class required to override newInstanceOfMyType method to give away instance of its type and then also override copyFrom method to produce a perfect clone. Now people might argue that why an abstract Clone method cant do the same job? Yes it can. But I required cloned instance of subclass as well as an empty instance(without copying anything from current) so I came up with this architecture.

Accessing objects through their interfaces

What does it really mean? I am reading design pattern book. It says
objects are accessed solely through their interfaces, and I am not able to get my head around it, can some body give me an example (Will really appreciate if its in C#)
What do we really achieve by using it?
Thanks
If you have a class called Espson and it implements an interface called IPrinter then you can instantiate the object by it's interface.
IPrinter printer = new Espson();
Epson may have a number of methods that are not part of the IPrinter interface but you may not care. All you may want to do is call a method defined in the IPrinter interface called Print
So then I can pass the class to a method called PrintDocument(IPrinter printer) and the method doesn't care what type of printer it is, it just knows it has a method called Print
The problem is the interface has several meanings. In this case the author is talking that objects must be accessed through public methods (in C# through public properties also) only.
(Of course, inheritors may use protected methods).
Public methods/properties form the public interface of a class. It's not the same interface that described by interface keyword in C#.
That really depends. If the variable is of type "interface", then in that case the object can be accessed by the interface type only.
Let's consider an example - Suppose I have an interface as defined below -
interface IMyInterface
{
string B();
}
and if I implement this interface using a class "MyClass" as shown below -
public class MyClass:IMyInterface
{
public string B()
{
return "In Class";
}
}
public class MyAnotherClass:IMyInterface
{
public string B()
{
return "In Another Class";
}
}
and I create an instance of the class using the interface as shown below
IMyInterface myinst = new MyClass();
then in the above case I can only get access to the Method B() using variable myinst which contains a reference to MyClass type.
Going further, let's say I have a method that takes a parameter of type IMyInterface as shown below -
public class UseOfInterface{
public void InterfaceUse(IMyInterface myPara)
{
myPara.B();
}
}
and I call this method as shown below -
IMyInterface myInst = new MyClass();
IMyInterface myAnotherInst = new MyAnotherClass();
UseOfInterface interfaceUse = new UseOfInterface();
interfaceUse.InterfaceUse(myInst); // returns "In Class"
interfaceUse.InterfaceUse(myAnotherInst); // returns "In Another Class"
Then, as shown above, it is decided at runtime as to which method is called using the Interface variable.
But if I had created a variable of type MyClass which would have contained a reference of type MyClass itself as shown below -
MyClass myinst = new MyClass();
then method B() can be accessed using the MyClass instance. So it depends what type of scenario you are dealing with.
Edit: Why Use Interfaces?
The main reason to use an interface is that it provides a contract to the class for which it is being implemented apart from the multiple inheritance support in C#. Let's can see an example where the contract providing can be helpful.
Suppose you have a class - "Car" in your assembly that you want to expose publicly, the definition of the class is as shown below
namespace CarNameSpace
{
public class Car()
{
public void Drive(IDriver driver)
{
if(driver.Age > 18)
{
driver.Drive();
}
}
}
}
As shown above, anyone who implements the IDriver interface can drive the car, which is defined below,
interface IDriver
{
string Age{get; set;}
string Name {get set;}
string Drive()
}
In turn to drive my car I would be exposing the IDriver interface to the outer world, so anyone who implements my interface can call the Car's Drive method, doesn't matter how he drives the car as shown below
public class PerfectDriver:IDriver
{
public PerfectDriver()
{
Name = "Vikram";
Age = 30;
}
public int Age{get; set;}
public string Name {get; set;}
public string Drive()
{
return "Drive's perfectly";
}
}
The Car class can be used as shown below
PerfectDriver perf = new PerfectDriver
Car myCar = Car();
myCar.Driver(perf);
An interface is a construct that describes the signature of the public members of an object. It contains declarations (declarations only, no implementation) of properties, methods and events that are guaranteed to be present on any object that implements that interface.
Here's a simple interface and a few classes that implement it. The interface "INamed" states simply that objects implementing the interface have a "Name" property that is a string.
public interface INamed{
string Name{get;}
}
public class Person : INamed{
public string Name{get;set;}
}
public class Place : INamed{
public string Name{get;set;}
}
public class Thing : INamed{
public string Name{get;set;}
}
...And a simple method that accepts a parameter of that interface type.
static void PrintName(INamed namedObject){
Console.WriteLine(namedObject.Name);
}
This "PrintName" method can accept a parameter of any type that implements that interface. The advantage of "accessing objects by their interface" is that it infuses your application with a certain flexibility, accessing these interfaces as opposed to their concrete types allows you to operate on these objects without having to know what they really are.
I could, for instance choose to operate on the IDbCommand interface as opposed to a concrete SqlCommand and much of what I write in this manner will be useful when working with a variety of database providers.
The simple idea is that you don't need to know if you're in a car or a boat because you can drive anything with a wheel and pedals.
The interface refers to what the object exposes to users of the object. An object will be an instance of a class which will have its own interface and possibly implement one or more other interfaces.
While languages such as C# allow you to define things called interfaces, those are distinct from the interface referred to in the statement that objects are accessed through their interfaces. In a language such as Scala, for instance, what C# calls an interface is called a trait. Most design patterns do involve the use of defined interfaces, i.e. public interface <interface name>, but again, those are distinct from what is meant in the original statement.
Suppose I define the following class in C#:
public class MyType
{
public void Method1()
{
...
}
private void Method2()
{
...
}
public int Method3()
{
...
}
}
Then the interface through which I interact with the class is the two methods it exposes, void Method1 and int Method2 and the implicit parameterless constructor.
Now, suppose I define the following interfaces and class:
public interface IInterface1
{
void Method1();
}
public interface IInterface2
{
int Method3();
}
public class MyType2 : IInterface1, IInterface2
{
public void Method1()
{
...
}
private void ADifferentMethod()
{
...
}
public int Method3()
{
...
}
}
The interface through which a user interacts with instances of MyType2 is the same as that through which a user interacts with instances of MyType1 (except for the different constructors) because the signatures of the public methods (and other public members) are identical : void Method1 and int Method3.

Abstract class constructor in C#

In c# we can't create an obeject of a abstact class or interface it means abstract class do not have any constructor, is it true ?
or if it have then what is it's purpose there?
As others have said, abstract classes usually have constructors (either explicitly or the default one created by the compiler) - and any derived class constructor will have to chain through the abstract class's constructor in the normal way. That's the important bit... suppose you have an abstract class which stores the name associated with an instance - because you always want a name, and you don't want to write the Name property in each concrete derived class. You might provide a constructor which takes that name and assigns it to a field... and then every subclass constructor would have to go through that constructor, so that you still knew you'd always have a name. If you want to know more about constructor chaining, read my article on it.
Here's an example of that:
public abstract class DemoBase
{
private readonly string name;
public string Name { get { return name; } }
protected DemoBase(string name)
{
this.name = name;
}
// Abstract members here, probably
}
public class FixedNameDemo : DemoBase
{
public FixedNameDemo()
: base ("Always the same name")
{
}
// Other stuff here
}
public class VariableNameDemo : DemoBase
{
public VariableNameDemo(string name)
: base(name)
{
}
// Other stuff here
}
To further answer your comment on BoltClock's answer, asbtract classes can't have private abstract methods, but they can have private constructors. Indeed, it's sometimes useful to have only private constructors in an abstract class, because it means the class can only be derived from within the program text of the same class. This allows you to create pseudo-enums:
public abstract class ArithmeticOperator
{
public static readonly ArithmeticOperator Plus = new PlusOperator();
public static readonly ArithmeticOperator Minus = new MinusOperator();
public abstract int Apply(int x, int y);
private ArithmeticOperator() {}
private class PlusOperator : ArithmeticOperator
{
public override int Apply(int x, int y)
{
return x + y;
}
}
private class MinusOperator : ArithmeticOperator
{
public override int Apply(int x, int y)
{
return x - y;
}
}
}
In this respect, an abstract private method/property could make sense - it could be accessed by the base class but provided by the derived classes within the same class's program text. However, it's prohibited by the specification. Usually, protected abstract members would solve the same problem - but not quite always.
Good question. Here's why Abstract classes need constructors even though they cannot be instantited.
In any Object oriented language like C#, object construction is an hierarchical process. Look at the code below. When you instantiate any object of type DerivedClass, it must construct the base object first before creating the object of typeof DerivedClass. Here the base class may or may not be an Abstract class. But even when you instantiate an object of a concrete type derived from an abstract class it will still need to call the constructor of the Base class before the object of DerivedClass type is created, hence you always need a constructor for Abstract class. If you have not added any constructor, C# compiler will automatically add a public parameterless constructor to the class in the generated MSIL.
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("BaseClass constructor called..");
}
}
public class DerivedClass : BaseClass
{
public DerivedClass()
{
Console.WriteLine("DerivedClass constructor called..");
}
}
DerivedClass obj = new DerivedClass();
//Output
//BaseClass constructor called..
//DerivedClass constructor called..
PS: Assuming, If Abstract base classes
are not allowed to have constructors
because they need not be instantiated,
the whole fundamentals of the object
oriented programming will go on toss.
The idea behind Abstract types are to
represent objects that have some
features and behaviours but not
complete as whole to allow independant
existence.
No. it means that operator new is not allowed to create object from this type of class.
The purpose might be that are allocated/initialized some properties of class.
abstract usually leave some methods to implement.
Regarding the interface, this structure holds only the signatures of method, delegates or events. That may be implemented in class that use interface. You cant create a object.
Read about new
EDIT:
What is the purpose of constructor in abstract class ?
When one class inherit another class, the parent class of it had to be created first while object is crated. In class do not implement some special constructor always is used default one [className()]. When you override some method then the implementation of functionality is taken form class which override the method. This is why method used in constructor should never be virtual. Same logic for abstract class, such class can have a lot of functionality, and only one method that should be implemented by child class.
Abstract classes have constructors but you can't call them directly as you can't directly instantiate abstract classes.
To answer your comment, the concept of a private abstract method or property makes no sense, because private prevents anybody else from accessing it, and abstract prevents itself from accessing it. So there would essentially be no possible way to call it.
EDIT: see Jon Skeet's answer on private constructors. Private members of other kinds cannot exist in abstract classes, though.
Abstract classes do have constructors. When you create an instance of a derived class, its parent class' constructors are called. This applies to classes derived from abstract classes as well.

Categories