Dynamic Casting - vineethkumarv/SystemVerilog_Course GitHub Wiki
Dynamic Casting
Dynamic casting is the concept of changing one data type to another that do not exist generally.
- It is done while run time.
- Using $cast keyword we can achieve dynamic casting.
- $cast can be a function or a task.
Syntax:   $cast(destination,source);
$cast as a task
To use $cast as a task we just use $cast without assigning it to any variable.
- As task has no return value the task implementation of cast do not return any value.
- and any error in casting like non-compatible sizes with lead to error.
syntax:   $cast(destination,source);
Code Snippet
module DC_task;                                                      
typedef enum {red=20,blue=30,green=40}color;                                                        
int a,b;                                                                                            
color c,d;                                   
initial begin                                                                                       
  a=40;
  $cast(d,"hi"); //throws error while run time, to avoid we use function
  $cast(c,a);//task implementation                                         
  $display("color is %0d and return value is %0d",c,d);                                                    
end                                                                                                 
endmodule 
output:

             Fig.output of cast as task implementation
$cast as a function
To use $cast as a function we use it where a value is to be returned.
- $cast is used as a function to skip the error if casting fails.
- The default value returned is 0,so no error is thrown.
Syntax: variable = $cast(destination,source);
Code Snippet
   module DC_fun;                                                                                      
   typedef enum {red=20,blue=30,green=40}color;                                                        
   int a,b;                                                                                            
   color c;                                                                                            
   initial begin                                                                                       
     a=40;                                                                                             
     b=$cast(c,"hi");//default function value is 0                                                     
     $display("color is %0d and return value is %0d",c,b);                                             
     //why function means if cast doesnot happen the program still runs with no error                  
   end                                                                                                 
   endmodule    
output:

         Fig.output of cast as function implementation