Given a generic class in C# like this one:

public class MyType<T>
{
    public MyType(T value) { }
}

You will need to spec­ify what the type T should be when you call the constructor:

var myObj = new MyType<int>(42);

The com­piler is not able to use type infer­ence to infer the type T to be int.

Now, this is inter­est­ing as type infer­ence is sup­ported by any other generic method, so if you were to cre­ate a fac­tory class for MyType<T> you could indeed make use of type infer­ence like this:

public class MyTypeFactory
{
    public static MyType<T> Create<T>(T value)
    {
        return new MyType<T>(value);
    }
}
...
var myObj = MyTypeFactory.Create(42); // returns MyType<int>

Some argue that it’s not pos­si­ble because of the pos­si­ble pres­ence of other over­loaded con­struc­tors (or for that mat­ter a non-generic ver­sion of MyType), but at the end of the day the con­struc­tor is a method like any other and the cited ambi­gu­ity can also appear with nor­mal generic methods:

public void Foo(short value) {}
public void Foo(int value) {}
public void Foo(long value) {}
public void Foo(double value) {}
public void Foo<T>(T value) {}
…
Foo(42); // which Foo is called? Foo(int) of course!

So amidst all that ambi­gu­ity the com­piler is able to infer the type for the Foo method, so what’s so spe­cial about the con­struc­tor? Am I miss­ing some­thing obvi­ous here?

Luck­ily, as Eric Lip­pert stated in his answer to my ques­tion here, the rea­son the con­struc­tor does not sup­port type infer­ence is a prac­ti­cal one – the ben­e­fit of the fea­ture does not out-weight the cost of its imple­men­ta­tion and it is some way behind other pos­si­ble fea­tures in terms of pri­or­ity. Whilst he did say that this fea­ture is on the list, con­sid­er­ing that the ‘theme’ of the next C# release (5.0) is rumoured to be meta-programming, there’s a good chance we won’t be see­ing type infer­ence in the C# con­struc­tor for some time yet!

Ref­er­ences:

Jon Skeet’s Brain­teasers + Answers

Stack­Over­flow ques­tion – why can’t the C# con­struc­tor infer type

Share

For a while now I’ve been curi­ous as to whether the CLR uses the Thread­Pool to exe­cute a del­e­gate when Begin­In­voke is called:

private void InvokeFunc(Func<int> func)
{
    func.BeginInvoke(null, null); // does this execute on a threadpool thread?
}

Whilst com­mon sense dic­tates that this must surely be true, I couldn’t be cer­tain since I haven’t man­aged to find any con­fir­ma­tion in the documentations.

Thanks to Jon Skeet and Jeff Ster­nal who pro­vided the answer to my ques­tion and a link to the MSDN arti­cle which con­firms it:

If the Begin­In­voke method is called, the com­mon lan­guage run­time (CLR) queues the request and returns imme­di­ately to the caller. The tar­get method is called asyn­chro­nously on a thread from the thread pool.

This of course, means that if your del­e­gate is likely to take a while to exe­cute you should not call Begin­In­voke on the del­e­gate to avoid block­ing the Thread­Pool threads, instead you could cre­ate a new thread or use a Smart­Thread­Pool instance. I’ve dis­cussed these aspect in more detail here and here if you’re interested.

Ref­er­ences:

MSDN – Asyn­chro­nous Pro­gram­ming using Delegates

Stack­Over­flow Ques­tion – Does Func.BeginInvoke use the ThreadPool

Share

Yet another use­ful method on the Enu­mer­able class, the SequenceE­qual method does exactly what it says on the tin and tells you whether or not two sequences are of equal length and their cor­re­spond­ing ele­ments are equal accord­ing to either the default or sup­plied equal­ity comparer:

var list1 = new List<int>() {0 ,1 ,2, 3, 4, 5, 6 };
var list2 = new List<int>() {0 ,1 ,2, 3, 4, 5, 6 };
var list3 = new List<int>() {6 ,5 ,4, 3, 2, 1, 0 };

list1.SequenceEqual(list2); // returns true
list1.SequenceEqual(list3); // returns false

As you know, for ref­er­ence types the default equal­ity com­parer com­pares the ref­er­ence itself hence:

class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}
…
Pet pet1 = new Pet { Name = "Turbo", Age = 2 };
Pet pet2 = new Pet { Name = "Peanut", Age = 8 };

// Create two lists of pets.
var pets1 = new List<Pet> { pet1, pet2 };
var pets2 = new List<Pet> { pet1, pet2 };
var test1 = pets1.SequenceEqual(pets2); // returns true

var pets3 = new List<Pet> { pet1, new Pet { Name = "Peanut", Age = 8 } };
var test2 = pets1.SequenceEqual(pets3); // returns false

There are a num­ber of ways you can get around this, including:

  • make Pet a value type, i.e. struct
  • make Pet imple­ment the IEquat­able interface
  • cre­ate an Equal­i­ty­Comparer and use the over­loaded SequenceE­qual method which takes an equal­ity comparer

Here is an inter­est­ing usage of the SequenceE­qual method to help find dupli­cates in a list of lists (see this Stack­Over­flow ques­tion) as pro­vided by Judah Himango:

var lists = new List<List<int>>()
{
    new List<int>() {0 ,1, 2, 3, 4, 5, 6 },
    new List<int>() {0 ,1, 2, 3, 4, 5, 6 },
    new List<int>() {0 ,1, 4, 2, 4, 5, 6 },
    new List<int>() {0 ,3, 2, 5, 1, 6, 4 }
};

var duplicates = from list in lists
                 where lists.Except(new[] { list }).Any(l => l.SequenceEqual(list))
                 select list;
Share

Whilst read­ing through the answers for this ques­tion on Stack­Over­flow, I came across the IsDigit and IsNum­ber meth­ods on the Char class. And look­ing at the Char class in more detail there are many more use­ful meth­ods on the Char class which I didn’t realise was there before, such as:

IsDigit checks if a char­ac­ter is a radix-10 digit, i.e. 0–9.

IsNum­ber checks if a char­ac­ter can be cat­e­go­rized as a num­ber, includ­ing dig­its, char­ac­ters, frac­tions, sub­scripts, cur­rency numer­a­tors, etc.

Get­Nu­mer­ic­Value con­verts a char­ac­ter to a double.

GetU­ni­code­Cat­e­gory cat­e­go­rizes a char­ac­ter into a group iden­ti­fied by one of the Uni­code­Cat­e­gory enum. This is an inter­est­ing method as it allows you to check whether a given char­ac­ter is a cur­rency sym­bol or maths sym­bol for instance:

char.GetUnicodeCategory('+').Dump();  // UnicodeCategory.MathSymbol
char.GetUnicodeCategory('-').Dump();  // UnicodeCategory.DashPunctuation
char.GetUnicodeCategory('{').Dump();  // UnicodeCategory.OpenPunctuation
char.GetUnicodeCategory('$').Dump();  // UnicodeCategory.CurrencySymbol
char.GetUnicodeCategory('}').Dump();  // UnicodeCategory.ClosePunctuation

IsCon­trol checks whether a char­ac­ter is a con­trol character.

IsLet­ter checks whether a char­ac­ter is a uni­code letter.

IsLet­terOrDigit checks whether a char­ac­ter is a let­ter or a dec­i­mal digit.

IsLower and IsUp­per checks whether a char­ac­ter is lower or upper case letter.

IsWhite­Space checks if a char­ac­ter is a white space.

What’s even bet­ter, each of the meth­ods are over­loaded so that you can pass in the char to test or a string and an accom­pa­ny­ing int to spec­ify the posi­tion of the char in the string, e.g. IsDigit(char) and IsDigit(string, int).

Share

Another good ques­tion on Stack­Over­flow, and even bet­ter answer from Steven (miles bet­ter than what I man­aged!), the ques­tion was around how to imple­ment an exten­sion method to check whether a cer­tain method has a par­tic­u­lar attribute applied to it, mainly for the pur­pose of unit testing.

In his answer, Steven pro­vided a cou­ple of use­ful exten­sion meth­ods to get the meta­data of a method using lambda expres­sion and then check whether an attribute with the spec­i­fied type has been applied to it:

public static MethodInfo GetMethod<T>(this T instance, Expression<Func<T, object>> methodSelector)
{
    // Note: this is a bit simplistic implementation. It will
    // not work for all expressions.
    return ((MethodCallExpression)methodSelector.Body).Method;
}

public static MethodInfo GetMethod<T>(this T instance, Expression<Action<T>> methodSelector)
{
    return ((MethodCallExpression)methodSelector.Body).Method;
}

public static bool HasAttribute<TAttribute>(this MemberInfo member) where TAttribute : Attribute
{
    var attributes = member.GetCustomAttributes(typeof(TAttribute), true);
    return attributes.Length > 0;
}

Nice, eh? I thought so too! Don’t for­get to give him some much deserved up vote!

Share