PrepAway - Latest Free Exam Questions & Answers

Which line of code should you use?

You have a class named Customer and a variable named customers.
You need to test whether the customers’ variable is a generic list of Customer objects.
Which line of code should you use?

PrepAway - Latest Free Exam Questions & Answers

A.
Option A

B.
Option B

C.
Option C

D.
Option D

Explanation:
If you want to check if it’s an instance of a generic type:
return list.GetType().IsGenericType;
If you want to check if it’s a generic List<T>:return list.GetType().GetGenericTypeDefinition() == typeof(List<>);
Testing if object is of generic type in C#
http://stackoverflow.com/questions/982487/testing-if-object-is-of-generic-type-in-c-sharp

7 Comments on “Which line of code should you use?

  1. Seamus says:

    The answer is A

    Tested in VS.

    public class Question7
    {
    public void TestCustomerObject()
    {
    Customer cust = new Customer();
    List custList = new List();
    custList.Add(cust);

    if(custList.GetType() is List)
    {
    Console.WriteLine(“True”);
    }
    else
    {
    Console.WriteLine(“False”);
    }
    }

    public class Customer
    {
    public string name { get; set; }
    }

    }




    4



    2
  2. Blasphem says:

    namespace ConsoleApplication
    {
    class Program
    {
    static void Main(string[] args)
    {
    var customers = new List();

    Console.WriteLine(“customers is List : ”
    + (customers is List));

    Console.WriteLine(“customers is List[] : ”
    + (customers is List[]));

    Console.WriteLine(“customers.GetType() is List[] : ”
    + (customers.GetType() is List[]));

    Console.WriteLine(“customers.GetType() is List : ”
    + (customers.GetType() is List));

    Console.ReadLine();
    }
    }

    class Customer
    {
    }
    }

    // Display
    customers is List : True
    customers is List[] : False
    customers.GetType() is List[] : False
    customers.GetType() is List : False




    8



    0

Leave a Reply