Get a variable from a class that inherits another - c#

I have an arbitrary amount of classes, classThatInherits, anotherClassThatInherits, etc. that inherit classToBeInherited.
I then have a method, b, that needs to be able to access myValue from the classes that inherit classToBeInherited. How can I achieve this, without casting?
//This class will be inherited by other classes
public class classToBeInherited {
public bool isSomething { get; set; }
}
//This class with inherit 'classToBeInherited'
public class classThatInherits : classToBeInherited {
public int myValue { get; set; } //this needs to be accessable...
}
//...And so will this class
public class anotherClassThatInherits : classToBeInherited {
public int myValue { get; set; }
}
private class normalClass {
private void a() {
classThatInherits cti = new classThatInherits();
b(cti);
anotherClassThatInherits acti = new anotherClassThatInherits();
b(acti);
}
private void b(classToBeInherited c) {
//***
//get myValue from the classes that inherit classToBeInherited
//***
}
}

Move myValue to classToBeInherited:
public class classToBeInherited {
public bool isSomething { get; set; }
public abstract int myValue { get; set; }
}
Then in classThatInherits and anotherClassThatInherits use public override int myValue { get; set; } to implement that property.
Ofcorse, if myValue is needed in only some of the classes, then you can have virtual and not abstract property.

var a = c as anotherClassThatInherits;
if (a != null)
{
var myValue = a.myValue;
}
I don't know why you don't want to do casting, but it's very common to have code like above.
UPDATED
If you really don't want casting, you can use reflection (but you still need to know the type of anotherClassThatInherits)
var getter = typeof(anotherClassThatInherits).GetProperty("myValue").GetGetMethod();
var myValue = getter.Invoke(c, null);

Related

Generic type parameters C# - How to generic class return type

Suppose I have two classes and both contain the same fields
Class A
{
public string Name { get; set; }
public int Designaton { get; set; }
}
Class B
{
public string Name { get; set; }
public int Designation { get; set; }
}
And I have one interface and two classes which are inherited from interface
public interface IDeprt
{
object BindData();
}
And two extractor classes:
public classAItem : IDeprt
{
public object BindData()
{
return new A()
{
// mapping operation
}
}
}
public classBItem : IDeprt
{
public object BindData()
{
return new B()
{
//same mapping operation
}
}
}
My question, how can I implement this in generic way using <T> .
Both classes are doing same operation only return type change. If I am doing in the above way there is lot of duplication of code.
Make your ITem interface and also BindData generic make them use the same generic parameter.
public interface IItem<T>
{
T BindData();
}
Then implement the subclasses like below :
public class AItem : ITem<A>
{
public A BindData(){
return new A(){
// mapping operation
}
}
}
public class BItem : ITem<B>
{
public B BindData(){
return new B(){
//same mapping operation
}
}
}
Edit : As the question evolves.
Make a shared base class for A and B classes.
public abstract class CommonItem
{
public string Name { get; set; }
public int Designaton { get; set; }
}
class A : CommonItem
{
}
class B : CommonItem
{
}
Then make class with a method that accepts a generic parameter with new and CommonItem constraints.
public class Binder
{
public T BindData<T>() where T: CommonItem, new()
{
return new T()
{
// you can access the properties defined in ICommonItem
}
}
}
Usage :
var binder = new Binder();
var boundA = binder.BindData<A>();
var boundB = binder.BindData<B>();

Using reflection to cast unknown object to generic class

I have a method which takes an object as a parameter. Within that method I walk through that objects properties with reflection. Some properties are of a generic class type. I like to read a property of that generic class property, but I cannot cast it to a generic class.
public abstract class BaseClass
{
public int Id { get; set; }
}
public abstract class GenericClass<T>: BaseClass
{
public string Description { get; set; }
}
public class DerivedClassA: GenericClass<DerivedClassA>
{
public string A { get; set; }
}
public class DerivedClassB: GenericClass<DerivedClassB>
{
public string B { get; set; }
}
public class ReflectingClass: BaseClass
{
public string Code { get; set; }
public DerivedClassA DerA { get; set; }
public DerivedClassB DerB { get; set; }
}
public static void Reflecting(object obj)
{
var t = GetType(obj)
foreach (var pi in t.GetProperties())
{
if (obj.GetType().BaseType.GetGenericTypeDefinition() == typeof(GenericClass<>)
{
var genClassObjProperty = ((GenericClass<T>)obj).Description; // Error, cannot do this at all !!!
}
}
}
What I want is for the code to walk to the properties and whatever the derived class actually is get the Description property of the GenericClass it is derived from.
I am using a generic class, because elsewhere in the code I call methods by their derived class and get the proper class type without resorting to all kinds of cast and passing types. I.e:
DerivedClassA.DoSomething()
instead of
BaseClass.DoSomething<DerivedClassA>()
or
BaseClass.DoSomething(type derivedClassType)
Take a look at this:
public static void Reflecting(object obj)
{
foreach (var pi in obj.GetType().GetProperties())
{
if (pi.PropertyType.BaseType.IsGenericType
&& pi.PropertyType.BaseType.GetGenericTypeDefinition()
== typeof(GenericClass<>))
{
var propValue = pi.GetValue(obj);
if (propValue != null)
{
var description = propValue.GetType()
.GetProperty("Description").GetValue(propValue);
Console.WriteLine(description);
}
}
}
Console.ReadKey();
}
I think this is what you need.

Need solution regarding generic c# method

I am trying to make my method generic and I am stuck at a point and need your assistance. The code scenario is I have an abstract class say MyBaseAbs which contains common properties:
public abstract class MyBaseAbs
{
public string CommonProp1 { get; set; }
public string CommonProp2 { get; set; }
public string CommonProp3 { get; set; }
}
Now I have child classes:
public class Mychild1: MyBaseAbs
{
public string Mychild1Prop1 { get; set; }
public string Mychild1Prop2 { get; set; }
public string Mychild1Prop3 { get; set; }
}
and another child class:
public class Mychild2: MyBaseAbs
{
public string Mychild1Prop1 { get; set; }
public string Mychild2Prop2 { get; set; }
}
Now I have to create a common method which needs to perform some operations on the basis of Mychild1 and Mychild2, so what I did is:
public MyCustomClass SaveOperation<T>(T myObj)
where T : MyBaseAbs
{
SaveObject obj = new SaveObject();
}
so inside this method I need to write common code which does the mapping for SaveObject object according to the child object passed. How can I determine which object is passed and use properties accordingly.
One option would be to create a base Save function in your base class and make it virtual.
Then override the method in your child classes. This way when you call the Save method in your SaveOperation it should call the appropriate method from the correct child class.
public abstract class MyBaseAbs
{
public string CommonProp1 { get; set; }
public string CommonProp2 { get; set; }
public string CommonProp3 { get; set; }
public virtual void Save() { }
}
public class Mychild1: MyBaseAbs
{
public string Mychild1Prop1 { get; set; }
public string Mychild1Prop2 { get; set; }
public string Mychild1Prop3 { get; set; }
public override void Save() {
//Implementation for Mychild1
}
}
public class Mychild2: MyBaseAbs
{
public string Mychild1Prop1 { get; set; }
public string Mychild2Prop2 { get; set; }
public override void Save() {
//Implementation for Mychild2
}
}
If you can't modify your business objects, you can check the type of the concrete class in the SaveOperation method:
public MyCustomClass SaveOperation<T>(T myObj)
where T : MyBaseAbs
{
SaveObject obj = new SaveObject();
if (myObj is Mychild1) {
Mychild1 mychild1 = (Mychild1) myObj;
// Business logic for object of type Mychild1
} else if (myObje is Mychild2) {
Mychild2 mychild2 = (Mychild2) myObj;
// Business logic for object of type Mychild2
}
}
Notice that this is not a very solid solution as, if you are creating new objects that implement your abstract class, you will have to remeber to add another branch in the if statement.
As #BojanB mentioned, the obvious solution would be to create a virtual method in your base class and override it in the derived, but if you cannot modify the code there then you can create a method for each derived class and create a dictionary that maps each type to its method:
private Dictionary<Type, Action<MyBaseAbs, MyCustomClass>> _saveOperations =
new Dictionary<Type, Action<MyBaseAbs, MyCustomClass>>();
//You can then set an entry for each of your derived classes
_saveOperations[typeof(Mychild1)] = (myObj, myCustomObj) =>
{
//Mychild1-specific logic
};
public MyCustomClass SaveOperation(MyBaseAbs obj)
{
//do the common saving operations here
var result = new MyCustomClass();
//....
var actualType = obj.GetType();
if(_saveOperations.ContainsKey(actualType))
{
_saveOperations[actualType](obj, result);
}
return result;
}
You can then add an item to the dictionary for each derived class. It is the same concept as using the is operator but allows you to add methods for more derived types without modifying the original SaveOperation method
You can use C#'s As-Operator as follows:
Mychild1 child1 = myObj as Mychild1;
if(child1 != null) {
//Here you can use child1.Mychild1Prop1 forexample
}
Link to msdn: https://msdn.microsoft.com/en-us/library/cscsdfbt.aspx

extending a class that already inherits another class

I am inheriting some System.Windows.Forms-Control (about 10 pieces).
Each of them gets some custom extensions, but most of the extension will be the same for each control.
Actually I have to code the same functionality separate for each of them.
This is a lot of copy+paste and difficult to maintain.
class MyButton : Button
{
//this is only in MyButton
public int ButtonProperty { get; set; }
public object Property1 { get; set; }
public object Property2 { get; set; }
public void MakeInvisible()
{
this.Visible = false;
}
}
class MyLabel : Label
{
//this is only in MyLabel
public bool LabelProperty { get; set; }
//same propertys and methods as in MyButton
public object Property1 { get; set; }//copy+paste
public object Property2 { get; set; }//copy+paste
public void MakeInvisible()//copy+paste
{
this.Visible = false;
}
}
What I am searching for is a way to extend all of the derived classes like you can do with an interface or extension method. But I also want to have properties and access the base class (Control)
This is what I am dreaming about:
class MyButton : Button, MyExtension
{
//this is only in MyButton
public int ButtonProperty { get; set; }
}
class MyLabel : Label, MyExtension
{
//this is only in MyLabel
public bool LabelProperty { get; set; }
}
//Extension for all classes inherited from Control
class MyExtension : Control
{
public object Property1 { get; set; }
public object Property2 { get; set; }
public void MakeInvisible()
{
this.Visible = false;
}
}
idea:
create a new type for common properties
give each control a property of that type
implementation:
// TypeConverter required for PropertyGrid in design mode
// found here: http://stackoverflow.com/a/6107953/1506454
[TypeConverter(typeof(ExpandableObjectConverter))]
public class MyExtension
{
// need reference to control to work with in methods
private Control _c;
public MyExtension(Control c)
{
_c = c;
}
// can be inhereted for different controls, if necessary
public string Property1 { get; set; }
public string Property2 { get; set; }
public void MakeInvisible()
{
_c.Visible = false;
}
}
// common interface of extended controls
public interface IExtended
{
MyExtension Extra { get; }
}
// MyButton implements extended interface
public class MyButton : Button, IExtended
{
public MyButton()
{
// create extended properties for button
Extra = new MyExtension(this);
}
// for designer serialization support
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public MyExtension Extra { get; private set; }
//this is only in MyButton
public int ButtonProperty { get; set; }
}
// common extension methods
public static class MyControlHelper
{
public static void MakeInvisible<TControl>(this TControl control) where TControl : Control, IExtended
{
control.Extra.MakeInvisible();
}
public static void Rename<TControl>(this TControl control) where TControl : Control, IExtended
{
control.Text = control.Extra.Property1;
}
}
C# doesn't support multi inheritance. You should try something like this - MyButton : MyExtension; and MyExtension : Button. In this case you will extend MyButton class with MyExtension and Button classes.
You can use extension methods for this purpose
public static class ControlHelper
{
public static void MakeInvisible(this Control c)
{
c.Visible = false;
}
}
and use it like this
var mb = new MyButton();
mb.MakeInvisible();
var ml = new MyLabel();
ml.MakeInvisible();
By using this approach you can generate extension methods for base classes and use it in derived classes.
Instead of inheriting from the Button and Label you could use composition.
class MyExtension
{
protected Control control;
public MyExtension(Control control)
{
this.control = control;
}
public object Property1 { get; set; }
public object Property2 { get; set; }
public void MakeInvisible()
{
this.control.Visible = false;
}
}
class MyButton : MyExtension
{
public MyButton(Button button):base(button){}
public int ButtonProperty { get; set; }
}
class MyLabel : Label
{
public MyButton(Label label):base(label){}
public bool LabelProperty { get; set; }
}
You could even make MyExtension abstract if you don't want any instances of it created. The main difference here is that you'll have to create a Button or Label to pass in and you might want to expose them as properties of your MyButton and MyLabel so you can get at their properties.
If you need to leverage protected methods and properties of the extended controls then you are out of luck, there is no way to acheive what you want without extensive copy and paste.
If you only need access to public methods and properties, then how about something along the following lines:
public interface IControlExtension
{
Foo MyProperty { get; set; }
Blah MyMethod();
}
public abstract class ControlExtension: IControlExtension
{
private Control owner;
private ControlExtension(Control owner)
{
Debug.Assert(owner != null);
this.owner = owner;
}
public static IControlExtension GetControlExtension(Control c)
{
if (c is Button ||
c is Label)
{
return new SimpleControlExtension(c);
}
if (c is Panel || ...
{
return new ContainerControlExtension(c);
}
}
public abstract Foo MyProperty { get; set; }
public abstract Blah MyMethod();
private class SimpleControlExtension: ControlExtension
{
public override Foo MyProperty { .... }
public override Blah MyMethod { ....
}
private class ContainerControlExtension: ControlExtension
{
public override Foo MyProperty { .... }
public override Blah MyMethod { .... }
}
}
Now, in all your extended controls, the copy and paste code is minimum:
public class MyButton : Button
{
public MyButton()
{
....
var controlExtension = ControlExtension.GetControlExtension(this);
}
public IControlExtension { get { return controlExtension; } }
}

How use the same method for different classes as parameter

I've got a function with List<> set as the parameter, which looks something like this:
private Double CalculateConsumption(List<GasConsumRecord> gasRecord)
{
...
foreach (var record in gasRecords){
var x = record.Counter;
var y = record.Pressure;
...
}
...
}
GasConsumRecord class has more properties but in this function I use only 2.
And I've got another class - AirConsumRecord which has the same 2 properties but other properties are different. Both classes have only properties, but no methods.
My question is: How can I use the same method for two different class List<> as parameter?
Thanks in advance.
You'll need your classes to implement the same interface, or derive from the same base class, which contains these two properties, then use a generic method with a type constraint:
If you use interfaces:
public interface IRecord {
int Counter { get; set; }
int Pressure { get; set; }
}
public class GasConsumRecord : IRecord {
public int Counter { get; set; }
public int Pressure { get; set; }
}
public class AirConsumRecord : IRecord {
public int Counter { get; set; }
public int Pressure { get; set; }
}
private Double CalculateConsumption<T>(List<T> records)
where T : IRecord
{
foreach (IRecord record in records){
var x = record.Counter;
var y = record.Pressure;
}
}

Categories

Resources