'C#, How to convert Object to Class Type
I am working on .NET CORE application. I have declare an Object that I need to cast or convert to Customer class type. I have scenario where based on bool value I need to change the type and return that.
error
System.InvalidCastException: 'Object must implement IConvertible
Customer Class
public class Customer
{
public string Name { get; set; }
public Customer GetCutsomer(){
//
}
}
'Object Casting`
public class MyService
{
public void CastType(){
Customer obj = new Customer();
var cus = GetCutsomer();
Object customer = new Object();
Convert.ChangeType(customer , cus.GetType());
}
}
Solution 1:[1]
You have some choices. Lets make a Customer and loose that fact by assigning to an object variable. And one that isnt a customer to show that case too
object o1 = new Customer();
object o2 = new String("not a customer");
so now we want to get back its 'customer'ness
First we can use as
Customer as1 = o1 as Customer;
Customer as2 = o2 as Customer;
- as1 ends up as a valid Customer pointer
- as2 ends up
nullsince o2 is not a Customer object
Or we can do a cast
var cast1 = (Customer)o1;
try {
var cast2 = (Customer)o2;
}
catch {
Console.WriteLine("nope");
}
- the first one succeeds
- the second one throws and InvalidCast exception
We can also ask about the object using is
if (o1 is Customer)
Console.WriteLine("yup");
if (o2 is Customer)
Console.WriteLine("yup");
This works too (answering question in comment)
object o1 = new Customer();
now
Customer c = (Customer)o1;
then later
o1 = new Order();
...
Order ord1 = (Order)o1;
Ie an Object pointer can point at any object.
This is inheritance at work. All class objects in c# are ultimately derived from Object, you just dont see it in your code. So an Object pointer can point at any class object
Solution 2:[2]
You should simply be able to safely cast any object to a class:
var obj = new Object();
var customer = (Customer)obj;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Azhari |
