0

Why is it required to have the (object) in the cast? It seems kind of counter-intuitive.

    public void GenerateForm<T>(T form)
    {
        if (form.GetType() == typeof(Form1))
        {
            Console.WriteLine(((Form1)(object)form).name);
        }
    }
stacka
  • 63
  • 1
  • 8
  • 1
    It might not make sense to convert `T` to `Form1`, but it makes sense to convert `T` to `Object` and `Object` to `Form1`. The compiler isn’t “smart” enough to know that the `if` changes things. Are you sure you don’t want `if (form is Form1 f)` and a simple `Console.WriteLine(f.name)`, though? – Ry- May 02 '18 at 02:40
  • 1
    It seems like you're sort of defeating the purpose of generics if you need to know if `T` is some specific type... – Rufus L May 02 '18 at 02:42

0 Answers0