« The SharePoint Pinterest-style Image Library | Main | SharePoint Saturday Adelaide update »
Monday
Jul092012

Test your C#: Generic overloaded constructors

I love languages.  Here's one for a language nut.

public class Response<T> {

    private T result;
    private string error;

    public Response(T result) { this.result = result; }
    public Response(string message) { this.error = message; }

}

 

You can use this generic class as a wrapper for returning data.

return new Response<int>(1000);

Or to return an abnormal result

return new Response<int>("Something has gone wrong");

 

Question 1

The fun part then, is what happens when you have this?

var result = new Response<string>("Is this a result or an error?");

What is result

 

Question 2


What about this:

public class Sample
{
    public static Response<T> GetSample<T>(T arg)
    {
        return new Response<T>(arg);
    }
}

and then:

var result = Sample.GetSample("Is this an error?");

What is result

Reader Comments (2)

I had no idea, so I had to make a console application from your snippets and the results surprised me.
The only guess I can make is that the compiler maintains the difference between a generic<string> parameter and a primitive<string> parameter.

Do you have any info on whether this guess is correct, or is there a more technical explanation?

July 12, 2012 | Unregistered CommenterJason

This has a lot to do with the compiler making an educated guess as to which overloaded constructor should be used for:

var result = new Response<string>("Is this a result or an error?");

It picks

Response<T>(string message)

as the winner constructor. One perculiar thing is that in VS.NET, if you look at the intellisense, when you use:

Response<Int> r = new Response<Int> ( ...

You'd get 2 constructor overloads.
But if you do:

Response < string > r = new Response < string >( ...

There's only 1 overload. The generic type one is actually shadowed.

In case 2.

The compiler dutifully calls - new Response<T>(arg), and passes the argument to the generic constructor. Even though a string is provided as the argument.

July 13, 2012 | Registered CommenterJohnLiu.NET

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>