Cast Class into Another Class or Convert Class to Another

Cast class into another class or convert class to another

What he wants to say is:

"If you have two classes which share most of the same properties you can cast an object from class a to class b and automatically make the system understand the assignment via the shared property names?"

Option 1: Use reflection

Disadvantage : It's gonna slow you down more than you think.

Option 2: Make one class derive from another, the first one with common properties and other an extension of that.

Disadvantage: Coupled! if your're doing that for two layers in your application then the two layers will be coupled!

Let there be:

class customer
{
public string firstname { get; set; }
public string lastname { get; set; }
public int age { get; set; }
}
class employee
{
public string firstname { get; set; }
public int age { get; set; }
}

Now here is an extension for Object type:

public static T Cast<T>(this Object myobj)
{
Type objectType = myobj.GetType();
Type target = typeof(T);
var x = Activator.CreateInstance(target, false);
var z = from source in objectType.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source ;
var d = from source in target.GetMembers().ToList()
where source.MemberType == MemberTypes.Property select source;
List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name)
.ToList().Contains(memberInfo.Name)).ToList();
PropertyInfo propertyInfo;
object value;
foreach (var memberInfo in members)
{
propertyInfo = typeof(T).GetProperty(memberInfo.Name);
value = myobj.GetType().GetProperty(memberInfo.Name).GetValue(myobj,null);

propertyInfo.SetValue(x,value,null);
}
return (T)x;
}

Now you use it like this:

static void Main(string[] args)
{
var cus = new customer();
cus.firstname = "John";
cus.age = 3;
employee emp = cus.Cast<employee>();
}

Method cast checks common properties between two objects and does the assignment automatically.

How convert own class to another own class

Here is a "working" code:

class Fish{}

class Bird{}

extension FishExtension on Fish {
Bird get toBird => Bird();
}

void main() {
Fish barracuda = Fish();
Bird eagle = barracuda.toBird;
print(eagle);
}

I'm not sure what your goal is and why do you need to convert a fish to a bird. But the error message is straightforward. You've tried to create an instance of bird class with a parameterless constructor passing an instance of a fish class.

As a result, the toBird method does nothing. It just creates a fresh new instance of bird class. There is no any kind of conversion here. Fish class hasn't any data (no fields), as a result, no real (useful) conversion possible here.

Update:

class Fish {
int speed;
Fish(this.speed);
}

class Bird {
double damage;
Bird(this.damage);
}

extension FishExtension on Fish{
Bird get toBird => Bird(this.speed.toDouble());
}

void main() {
Fish barracuda = Fish(10);
Bird eagle = barracuda.toBird;
print("Eagle: $eagle, eagle damage: ${eagle.damage}"); // Eagle: Instance of 'Bird', eagle damage: 10
}

How to cast Java class to another class

You can't cast a Class<Character> to Character. Your code

Character character = (Character) object;

should be

Class<Character> characterClass = (Class<Character>) object;

It looks like you want to create instance from its class. I recommend you to learn something about Java reflection. Maybe something like this Creating an instance using the class name and calling constructor

Converting object of a class to of another one

Use a conversion operator:

public static explicit operator FloatClass (DoubleClass c) {
FloatCass fc = new FloatClass();
fc.X = (float) c.X;
fc.Y = (float) c.Y;
fc.Z = (float) c.Z;
return fc;
}

And then just use it:

var convertedObject = (FloatClass) doubleObject;

Edit

I changed the operator to explicit instead of implicit since I was using a FloatClass cast in the example. I prefer to use explicit over implicit so it forces me to confirm what type the object will be converted to (to me it means less distraction errors + readability).

However, you can use implicit conversion and then you would just need to do:

var convertedObject = doubleObject;

Reference

Cast one class object to other class object

A good place to start is by reviewing the MSDN documentation on Casting and Type Conversions.

As there's no direct relationship between the two classes, you'll need to write a Conversion Operator. For example:

public class A
{
public int AValue { get; set; }
}

public class B
{
public int BValue { get; set; }

public static explicit operator B(A instanceOfA)
{
return new B { BValue = instanceOfA.AValue };
}
}

You could then write:

A instanceOfA = new A { AValue = 7 };
B instanceOfB = (B)instanceOfA;

// Will output "7"
Console.WriteLine(instanceOfB.BValue);

The documentation I've derived this example from is on MSDN, Using Conversion Operators.

If there was a direct relationship between the two classes, for example B derives from A, for example:

public class A
{
public int Value { get; set; }
}

public class B : A
{
public string OtherValueSpecificToB { get; set; }
}

You wouldn't then need any extra code if you wanted to cast from B to A:

B instanceOfB = new B { OtherValueSpecificToB = "b", Value = 3 };
A instanceOfBCastToA = (A)instanceOfB;

// Will output "3";
Console.WriteLine(instanceOfBCastToA.Value);
// Will not compile as when being treated as an "A" there is no "OtherValueSpecificToB" property
Console.WriteLine(instanceOfBCastToA.OtherValueSpecificToB);

Implement type casting from one class to another

The conversion needs to make sense first of all. Assuming it does, you can implement your own conversion operators, like in the example below:

#include <string>
#include <iostream>

class MyInt; // forward declaration

class MyString
{
std::string str;
public:
MyString(const std::string& s): str(s){}
/*explicit*/ operator MyInt () const; // conversion operator
friend std::ostream& operator<<(std::ostream& os, const MyString& rhs)
{
return os << rhs.str;
}
};

class MyInt
{
int num;
public:
MyInt(int n): num(n){}
/*explicit*/ operator MyString() const{return std::to_string(num);} // conversion operator
friend std::ostream& operator<<(std::ostream& os, const MyInt& rhs)
{
return os << rhs.num;
}
};

// need the definition after MyInt is a complete type
MyString::operator MyInt () const{return std::stoi(str);} // need C++11 for std::stoi

int main()
{
MyString s{"123"};
MyInt i{42};

MyInt i1 = s; // conversion MyString->MyInt
MyString s1 = i; // conversion MyInt->MyString

std::cout << i1 << std::endl;
std::cout << s1 << std::endl;
}

Live on Coliru

If you mark the conversion operators as explicit, which is preferable (need C++11 or later), then you need to explicitly cast, otherwise the compiler will spit an error, like

MyString s1 = static_cast<MyString>(i1); // explicit cast


Related Topics



Leave a reply



Submit