Convert data type from inherited classes in C#
Your problem stems from the fact that the base classes are poorly designed in the first place, in the following ways:
The hierarchy makes no sense. A behaviour is not a special kind of position. Prefer composition to inheritance.
Fields should never be public. Use properties, not fields.
"is" checks are runtime type checks; don't do runtime type checks for polymorphic behaviour; use virtual methods.
Let's redesign your hierarchy.
abstract class MyBehaviour
{
public Position Position { get; private set; }
public Handler Handler { get; private set; }
protected MyBehaviour(int x, int y, Handler handler) {
this.Position = new Position(x, y);
this.Handler = handler;
}
}
class Behaviour1 : MyBehaviour {
/* Whatever */
}
class Behaviour2 : MyBehaviour {
/* Whatever */
}
All right, and now when we want to execute the handler...
MyBehaviour b = whatever;
b.Handler.Enter();
Done. No temporary variable needed. No runtime type check. No "if". The behaviour provides a service; you use the service. You should not have to ask the behaviour its type in order to use the service it provides; if you do, something is probably wrong at the design level.
c# inheritance: change field data type and value in derived class
The way to do this is to make your property virtual in the base class:
public class class1
{
protected virtual DBContext DB { get; set; }
...
}
And then override it in the derived class:
public class class2 : class1
{
private DifferentDBContext DDB;
protected override DBContext DB
{
get { return DDB; }
set { DDB = value is DifferentDBContext ? (DifferentDBContext)value : null; }
}
}
This is assuming that DifferentDBContext
is a DBContext
.
changing property type with inherited classes
Give this a try.
public interface IBaseClass
{
int Id { get; set; }
object Value { get; set; }
}
public abstract class BaseClass<T> : IBaseClass
{
public int Id { get; set; }
public T Value { get; set; }
object IBaseClass.Value
{
get { return Value; }
set
{
// put some type checking and error handling here
Value = (T)value;
}
}
}
public class ClassInt : BaseClass<int>
{
// Properties specific for ClassInt, if you have any
// (otherwise you don't even need this class anymore)
}
Convert base class to derived class
No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass)
constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.
The code you posted using as
will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass
will evaluate to null
, since it's not an instance of DerivedClass
.
Casting object of inherited class to instance of inheriting type
A subclass is of type base class, but not the opposite. consider renaming them to
class Dog {}
class GermanShepard : Dog {}
This makes it clear that A German Sheppard is definitely a dog. But a dog is not necessarily a German Shepard.
writing the following is not possible, since the new dog could end up being another type of dog.
GermanShepard fred = new Dog(); //error!!
It might be a Shitzu or a Labrador. But you can always cast a German Shepard to a dog. Similarly you can always cast a Labrador to a dog.
Convert ListDerivedClass to ListBaseClass
The way to make this work is to iterate over the list and cast the elements. This can be done using ConvertAll:
List<A> listOfA = new List<C>().ConvertAll(x => (A)x);
You could also use Linq:
List<A> listOfA = new List<C>().Cast<A>().ToList();
Inherited classes — copy data
Following the object-oriented philosophy, a "PlaceDetail" object IS-A "Place" object, so you do not have to cast!
Place placeDetail = new PlaceDetail();
If you want to "upgrade" your object from Place to PlaceDetail, you can proceed in a variety of ways. For instance, you could build a method in a factory class to do that, and enter in this factory method the parameters you need to specify all "details".
First you must implement a "copy constructor" in PlaceDetail to initialize a PlaceDetail from a Place, ie.:
public PlaceDetail(Place p)
{
this.GoogleReference = p.GoogleReference;
this.GoogleID = p.GoogleID;
this.Name = p.Name;
this.Vicinity = p.Vicinity;
}
then, you could build your factory method as follows:
static class PlaceDetailFactory
{
public static PlaceDetail create(Place p, string url, string phone, string site)
{
PlaceDetail pd = new PlaceDetail(p);
pd.Url = url;
pd.InternationalPhoneNumber = phone;
pd.Website = site;
return pd;
}
}
Converting a List of Base type to a List of Inherited Type
If you have linq available you can do
var ListOfA = ListOfB.Cast<A>().ToList();
Convert derived class to base class
You can't - that's entirely deliberate, as that's what polymorphism is all about. Suppose you have a derived class which enforces certain preconditions on the arguments you pass to an overridden method, in order to maintain integrity... you don't want to be able to bypass that validation and corrupt its internal integrity.
Within the class itself you can non-virtually call base.AnyMethod()
(whether that's the method you're overriding or not) but that's okay because that's the class itself deciding to potentially allow its integrity to be violated - presumably it knows what it's doing.
Related Topics
How to Simulate a Mouse Click at a Certain Position on the Screen
How to Use Acrylic Accent in Windows 10 Creators Update
Correct Implementation of a Custom Config Section with Nested Collections
C# Constructing Parameter Query SQL - Like %
How to Validate Signature of Jwt from Jwks Without X5C
Explicitly Freeing Memory in C#
Wpf/C#: Where Should I Be Saving User Preferences Files
How to Connect and Use a SQLite Database from C#
Microsoft Visual Studio and C#: How to Visually Add Events to Controls
Raise Events in .Net on the Main UI Thread
Why Is There a Difference in Checking Null Against a Value in Vb.Net and C#
Delete a Single Record from Entity Framework
Differencebetween Iequalitycomparer<T> and Iequatable<T>
How to Create Xmlelement Attributes with Prefix
Mvc: Where to Put Business Logic
Best Way to Check for Nullable Bool in a Condition Expression (If ...)
How to Keep Single SQL Server Connection Instance Open for Multiple Request in C#