function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
chaithaly gowdachaithaly gowda 

can I cast event type to custom object type during run time

Hi

I have a requirement where i have to convert the sobject type to custom object type returned from quering the event object.
code:

global Database.QueryLocator start(Database.BatchableContext BC){
        
        return Database.getQueryLocator('Select Id, RecordTypeId, WhoId, WhatId, Subject, Location, IsAllDayEvent, ActivityDateTime, ActivityDate FROM Event);
        
    }
   
    global void execute(Database.BatchableContext BC, List<SObject> scope){
        for (sObject obj : scope) {
                Audit__c e=(AAudit__c)obj;
                try
                {
                    Database.SaveResult results = Database.insert(e, false);
                }catch(Exception ex){
                }
            }         
        update scope;
    }

this is giving me System.TypeException: Invalid conversion from runtime type Event to Audit__c .
here Audit__c is child of Event
Is it possible to convert this way , please let me know.

Thanks
ANUTEJANUTEJ (Salesforce Developers) 
Hi Chaithaly,

You can try checking the below link that states: "In general, all type information is available at runtime. This means that Apex enables casting, that is, a data type of one class can be assigned to a data type of another class, but only if one class is a child of the other class. Use casting when you want to convert an object from one data type to another."

>> https://salesforce.stackexchange.com/questions/64988/apex-cast-sobject-list-dynamically-to-a-specific-sobject-type#:~:text=This%20means%20that%20Apex%20enables,one%20data%20type%20to%20another.

I hope this helps.

Regards,
Anutej