csharp Generics Questions & Answers

Question 6: What will be the output of the following program?

class Program
{
    static void Main(string[] args)
    {
        Processor<int> p1 = new DataProcessor<int>();
        p1.Process(100);

        Processor<string> p2 = new DataProcessor<string>();
        p2.Process("TEST");
    }
}

class Processor<T>
{
    public void Process(T value)
    {
        Console.Write(value.GetType().Name + “ ”);
    }
}

class DataProcessor<U> : Processor<int>
{

} 

Question 7: What will be the output of the following program?

class Program
{
    static void Main(string[] args)
    {

        DataProcessor<string> p2 = new DataProcessor<string>();
        p2.Process(100);
    }
}

class Processor<T>
{
    public void Process(T value)
    {
        Console.Write(value.GetType().Name);
    }
}

class DataProcessor<U> : Processor<int>
{

}

Question 8: What will be the output of the following program?

static void Main()
{
    var numbers = new List<string> { 1, "two", "three"};

    // Iterate through the list.  
    foreach (var num in numbers)
    {
        Console.Write(num + “ “);
    }            
}
ADVERTISEMENT

Question 9: What will be the output of the following program?

class Program
{
    static void Main(string[] args)
    {
        Processor<int> p = new Processor<int>();
        p.BaseValue = 1;
        int result = p.Add(10);
            
        Console.Write(result);
    }
}

class Processor<T>
{        
    public int Add(int value) {
        return this.BaseValue + value;
    }
    public T BaseValue { get; set; }
}

Question 10: What will be the output of the following program?

class Program
{
    static void Main(string[] args)
    {
        Processor<int> p = new Processor<int>();
        p.Process(100);
    }
}

class Processor<T> where T:class
{
    public void Process(T value)
    {
        Console.Write(value);
    }
}