Home > Back-end >  C#, How to convert Object to Class Type
C#, How to convert Object to Class Type

Time:03-18

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());
   }
}

CodePudding user response:

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");

CodePudding user response:

You should simply be able to safely cast any object to a class:

var obj = new Object();
var customer = (Customer)obj;
  • Related