Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the proper way to cast?

Tags:

c#

I have this interface:

public interface IEntity
{
    int Id{get;set;}
}

A class:

public class Customer: IEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

and this is my usage:

void Main()
{
    List<Customer> list =  new List<Customer>();
    IEntity obj = null;
    obj = new Customer() {Id = 4, Name="Jenny", Age =41};
    list.Add(obj as Customer);  /*Line #1*/     
    list.Add((Customer)obj); /*Line #2*/        
}

Which is considered best practice: Line #1 or Line #2?

like image 860
SerenityNow Avatar asked Dec 07 '22 06:12

SerenityNow


1 Answers

The () cast operator will throw an exception (InvalidCastException) if the source cannot be cast to the target type. The as operator will set the resulting variable to null if the cast cannot be completed.

like image 114
Jesse C. Slicer Avatar answered Dec 09 '22 16:12

Jesse C. Slicer