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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With