EzDevInfo.com

generics interview questions

Top generics frequently asked interview questions

List<> OrderBy Alphabetical Order

I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic List<>. For the sake of this example lets say I have a List of a Person type with a property of lastname. How would I sort this List using a lambda expression?

List<Person> people = PopulateList();
people.OrderBy(???? => ?????)

Source: (StackOverflow)

Create Generic method constraining T to an Enum

I'm building a function to extend the Enum.Parse concept that

  • Allows a default value to be parsed in case that an Enum value is not found
  • Is case insensitive

So I wrote the following:

public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
    if (string.IsNullOrEmpty(value)) return defaultValue;
    foreach (T item in Enum.GetValues(typeof(T)))
    {
        if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
    }
    return defaultValue;
}

I am getting a Error Constraint cannot be special class 'System.Enum'.

Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the Parse function and pass a type as an attribute, which forces the ugly boxing requirement to your code.

EDIT All suggestions below have been greatly appreciated, thanks.

Have settled on (I've left the loop to maintain case insensitivity - I am usng this when parsing XML)

public static class EnumUtils
{
    public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
        if (string.IsNullOrEmpty(value)) return defaultValue;

        foreach (T item in Enum.GetValues(typeof(T)))
        {
            if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
        }
        return defaultValue;
    }
}

EDIT: (16th Feb 2015) Julien Lebosquain has recently posted a compiler enforced solution below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page.


Source: (StackOverflow)

Advertisements

Java Generics: What is PECS?

I came across PECS (short for Producer extends and Consumer super) while reading up on generics.

Can someone explain to me how to use PECS to resolve confusion between extends and super?


Source: (StackOverflow)

What is a raw type and why shouldn't we use it?

Questions:

  • What are raw types in Java, and why do I often hear that they shouldn't be used in new code?
  • What is the alternative if we can't use raw types, and how is it better?

Source: (StackOverflow)

List or IList

Can anyone explain to me why I would want to use IList over List in C#?

Related question: Why is it considered bad to expose List<T>


Source: (StackOverflow)

Why does C# forbid generic attribute types?

This causes a compile-time exception:

public sealed class ValidatesAttribute<T> : Attribute
{

}

[Validates<string>]
public static class StringValidation
{

}

I realize C# does not support generic attributes. However, after much Googling, I can't seem to find the reason.

Does anyone know why generic types cannot derive from Attribute? Any theories?


Source: (StackOverflow)

How do I clone a generic list in C#?

I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do list.Clone().

Is there an easy way around this?


Source: (StackOverflow)

Get generic type of class at runtime

How can I achieve this?

public class GenericClass<T>
{
    public Type getMyType()
    {
        //How do I return the type of T?
    }
}

Everything I have tried so far always returns type Object rather than the specific type used.


Source: (StackOverflow)

How to Sort a List by a property in the object

I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a list of this Order class:

List<Order> objListOrder = new List<Order>();
GetOrderList(objListOrder); // fill list of orders

Now I want to sort the list based on one property of the Order object, for example I need to sort it by the order date or order id.

How can i do this in C#?


Source: (StackOverflow)

What is the point of the diamond operator in Java 7?

The diamond operator in java 7 allows code like the following:

List<String> list = new LinkedList<>();

However in Java 5/6, I can simply write:

List<String> list = new LinkedList();

My understanding of type erasure is that these are exactly the same. (The generic gets removed at runtime anyway).

Why bother with the diamond at all? What new functionality / type safety does it allow? If it doesn't yield any new functionality why do they mention it as a feature? Is my understanding of this concept flawed?


Source: (StackOverflow)

How to get the type of T from a generic List?

Let say I have a List<T> abc = new List<T>; inside a class public class MyClass<T>//....

Later, when I initialize the class, the T becomes MyTypeObject1. So I have a generic list, List< MyTypeObject1 >.

I would like to know, what type of object the list of my class contain, e.g. the list called abc contain what type of object?

I cannot do abc[0].GetType(); because the list might contain zero elements. How can I do it?


Source: (StackOverflow)

Can't operator == be applied to generic types in C#?

According to the documentation of the == operator in MSDN,

For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings. User-defined value types can overload the == operator (see operator). So can user-defined reference types, although by default == behaves as described above for both predefined and user-defined reference types.

So why does this code snippet fail to compile?

void Compare<T>(T x, T y) { return x == y; }

I get the error Operator '==' cannot be applied to operands of type 'T' and 'T'. I wonder why, since as far as I understand the == operator is predefined for all types?

Edit: Thanks everybody. I didn't notice at first that the statement was about reference types only. I also thought that bit-by-bit comparison is provided for all value types, which I now know is not correct.

But, in case I'm using a reference type, would the the == operator use the predefined reference comparison, or would it use the overloaded version of the operator if a type defined one?

Edit 2: Through trial and error, we learned that the == operator will use the predefined reference comparison when using an unrestricted generic type. Actually, the compiler will use the best method it can find for the restricted type argument, but will look no further. For example, the code below will always print true, even when Test.test<B>(new B(), new B()) is called:

class A { public static bool operator==(A x, A y) { return true; } }
class B : A { public static bool operator==(B x, B y) { return false; } }
class Test { void test<T>(T a, T b) where T : A { Console.WriteLine(a == b); } }

Source: (StackOverflow)

IEnumerable and Recursion using yield return

I have an IEnumerable<T> method that I'm using to find controls in a WebForms page.

The method is recursive and I'm having some problems returning the type I want when the yield return is returnig the value of the recursive call.

My code looks as follows:

    public static IEnumerable<Control> 
                               GetDeepControlsByType<T>(this Control control)
    {
        foreach(Control c in control.Controls)
        {
            if (c is T)
            {
                yield return c;
            }

            if(c.Controls.Count > 0)
            {
                yield return c.GetDeepControlsByType<T>();
            }
        }
    }

This currently throws a "Cannot convert expression type" error. If however this method returns type IEnumerable<Object>, the code builds, but the wrong type is returned in the output.

Is there a way of using yield return whilst also using recursion?


Source: (StackOverflow)

Passing a single item as IEnumerable

Is there a common way to pass a single item of type T to a method which expects an IEnumerable<T> parameter? Language is C#, framework version 2.0.

Currently I am using a helper method (it's .Net 2.0, so I have a whole bunch of casting/projecting helper methods similar to LINQ), but this just seems silly:

public static class IEnumerableExt
{
    // usage: IEnumerableExt.FromSingleItem(someObject);
    public static IEnumerable<T> FromSingleItem<T>(T item)
    {
        yield return item; 
    }
}

Other way would of course be to create and populate a List<T> or an Array and pass it instead of IEnumerable<T>.

[Edit] As an extension method it might be named:

public static class IEnumerableExt
{
    // usage: someObject.SingleItemAsEnumerable();
    public static IEnumerable<T> SingleItemAsEnumerable<T>(this T item)
    {
        yield return item; 
    }
}

Am I missing something here?

[Edit2] We found someObject.Yield() (as @Peter suggested in the comments below) to be the best name for this extension method, mainly for brevity, so here it is along with the XML comment if anyone wants to grab it:

public static class IEnumerableExt
{
    /// <summary>
    /// Wraps this object instance into an IEnumerable&lt;T&gt;
    /// consisting of a single item.
    /// </summary>
    /// <typeparam name="T"> Type of the object. </typeparam>
    /// <param name="item"> The instance that will be wrapped. </param>
    /// <returns> An IEnumerable&lt;T&gt; consisting of a single item. </returns>
    public static IEnumerable<T> Yield<T>(this T item)
    {
        yield return item;
    }
}

Source: (StackOverflow)

Check if a class is derived from a generic class

I have a generic class in my project with derived classes.

public class GenericClass<T> : GenericInterface<T>
{
}

public class Test : GenericClass<SomeType>
{
}

Is there any way to find out if a Type object is derived from GenericClass?

t.IsSubclassOf(typeof(GenericClass<>))

does not work.


Source: (StackOverflow)