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());
}
}
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;
null
since o2 is not a Customer objectOr we can do a cast
var cast1 = (Customer)o1;
try {
var cast2 = (Customer)o2;
}
catch {
Console.WriteLine("nope");
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With