Difference cast using "as" and "type cast"

5

A question about casting in C #, I see in many sources using cast in the following ways.

What's the difference between one and the other when using one way or another?

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

public class ClasseTeste : InterfaceTeste
{
    public int Id { get; set; }
    public string Nome { get; set; }
}

public class ClasseTestando
{
    public void Teste()
    {
        List<InterfaceTeste> objList = new List<InterfaceTeste>();
        for (var i = 0; i < 0; i++)
        {
            objList.Add(new ClasseTeste() { Id = i, Nome = "Nome" + 1 });
        }
        ClasseTeste classe1 = objList.Find(x => x.Id == 1) as ClasseTeste;
        ClasseTeste classe2 = (ClasseTeste)objList.Find(x => x.Id == 1);
    }
}
    
asked by anonymous 23.03.2018 / 20:28

2 answers

5

In this example neither is needed, so it makes no difference.

as

The as operator should be used when you are not sure that the operation will work. Consider that there will be a conversion attempt, but if it fails the object that should receive the value of that type will receive the null value. After using as it is essentially mandatory to check if the object is not null. Then you would. If you are not doing this check you probably did not need this casting , or you will have another error going forward, which may be a bigger problem figuring out what is going on.

The cost of this operator as is even lower, but when we check if it is not null it ends up getting more or less the same thing.

C # 6

Normally you would make a if to check if the value is null to decide what to do. In C # 6 there is an operator that does nothing if it is null . In some cases it is possible to use it to simplify the code, but not at all.

C # 7

You can use pattern matching and just create a new object when it confirms that the object type is the one expected.

C # 8

When you quit it will be a version that will no longer encourage the use of null types, so as should fall into disuse and give way to pattern matching . cast with parenthesis will still be useful.

Cast

The classic cast , the second, requires you to be absolutely sure that "conversion" will not fail. Whatever situation you know will not fail you can use it. In many cases the cost of using it is zero.

One way to be absolutely certain is to if before doing cast , but doing so is why you should use as . Make sure even if you need to check it is because you do not have it. If you do this the performance will be worse and you can enter race condition .

This is a case where you are only informing the compiler that you can guarantee that the type is the one the compiler expects. If your warranty does not conform at runtime the application will throw an exception that should not be handled, this is a programming error and should fix this error.

It also has the advantage of converting into type by value. These types can not be null, so as would not work. Of course, it does not include nullable value types.

It can do type conversions when it is implemented on its own type. The () operator can be implemented in types for explicit conversion (it is also possible implicitly where an operator is not used). as is only allowed where language naturally leaves, in natural conversions, usually only by making a derived type become a base type of it.

I will not say that it is never necessary, but for the future I would forget as .

    
24.03.2018 / 01:08
3

When you cast with the () operator, if the conversion fails, an exception of type InvalidCastException will be returned. Already when the as keyword is used, if the conversion fails the result will be null . Therefore the as keyword can only be used with reference types or nullable types.

See the following links:

  

Difference between cast and as - C #
link

     

As (C # Reference)
link

     

Operator () (C # Reference)
link

     

Cast conversions and type conversions (C # Programming Guide)
link

And, from C # 7, you can also use the is keyword, both to test the type and to do a conversion, like this:

string s = null;
if (objList.Find(x => x.Id == 1) is ClasseTeste ct)
{
   s = $"Id: {ct.Id}, Nome: {ct.Nome}";
}
  

is (C # Reference)
link

    
24.03.2018 / 00:20