Reputation: 1065
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?
Upvotes: 4
Views: 134
Reputation: 5676
You should only cast when you know what you are doing. Using an explicit cast, you are saying »Hey man! I know, that the type of the Object is x, but it really is y. So transformation would not do any harm«. Hence I would vote for as
because it's easier on the eyes - C# being a noisy brackety language.
Using the traditional cast operator with the brackets, throwing an exception if your guess was wrong - and so prooving, that you in fact did not know, what you were doing- is halfhearted like saying »Hey Boy, I know, what I am doing ... d'oh ... hahaha, I was just kiddin'«.
So, when you want to cast, do it like a man!
Upvotes: 0
Reputation: 3333
I do understand, that your usage example is probably somewhat simplified, but i think it is worth metioning, that if you have to do something like that in real life - then you are probably have a disign issue. Casting interface to its actual implementation is bad practice, and it should be avoided as much as possible (often it is possible).
If you absolutely have to cast: in your case you should use ()
operator. If there is an error in your logic using as
will hide it and result in NullReferenceException
later on, which is way harder to track than an invalid cast.
Upvotes: 3
Reputation: 20157
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.
Upvotes: 12