What is the correct throwing method?

I have this interface:

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

Grade:

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

and this is my use:

 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*/ } 

What is considered best practice: line number 1 or line number 2?

+4
source share
3 answers

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

+12
source

I understand that your use case is probably a little simplified, but I think it's worth guessing that if you need to do something like this in real life, then you probably have a setup problem. The casting interface to its actual implementation is bad practice and should be avoided as much as possible (often possible).

If you absolutely must quit: in your case, you must use the () operator. If there is an error in your logic using as , it will hide it and result in a NullReferenceException later, which is much harder to track than an invalid listing.

+3
source

You should show only when you know what you are doing. Using an explicit narthex, you say: β€œHey man! I know that the type of object is x, but it really is y. So the transformation will not do any harm.” Therefore, I would vote for as , because it was easier on the eyes - C # was the noisy language of braces.

Using the traditional casting operator with brackets, throwing an exception if your hunch was wrong - and so souring that you really didn't know what you were doing - half as they say: "Hey boy, I know what I'm doing. .. dr ... ha ha ha, I was just a kiddin. "

So, when you want to quit, do it like a man!

0
source

Source: https://habr.com/ru/post/1497306/


All Articles