-1

First one is working, while second shows an error, what is the difference? I read documentation, and didnt find anything about it, it not so crucial but want to know some features

public static string GetConcat2<T>(T q)
    {
        if(q.GetType() == typeof(A))
        {
            var z = q as A;
        }
        if (q.GetType() == typeof(A))
        {
            var z = (A)q;
        }
        return "!!!!";
    }
public interface CustomInteface
{
    string InterfaceProperty1 { get; set; }
    string InterfaceProperty2 { get; set; }
    string Concat();
}
public class A : CustomInteface
{
    public string InterfaceProperty1 { get; set; }
    public string InterfaceProperty2 { get; set; }
    public string Concat() {
        return InterfaceProperty1 + InterfaceProperty2;
    }
}

1 Answers1

2

The line var z = (A)q; is throwing an error this means that the object q is not of type A. The way you are trying to cast is a bit awkward as well you should use one of the following patterns:

  • as followed by null check:

    var z = q as A;
    if (z == null) { /*the cast failed*/ }
    
  • is followed by explicit cast

    if (q is A)
    {
        var z = (A)q;
    }
    

Note the first pattern will return null if the cast fails and the second will throw an exception. This is why you only see the exception in the second case as the first is "silently" failing.

TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69