Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
   }
}
like image 481
K.Z Avatar asked Oct 14 '25 16:10

K.Z


1 Answers

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 null since 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

like image 69
pm100 Avatar answered Oct 17 '25 04:10

pm100