The Pragmatic Programmer

Tulisan iseng kalo ada waktu.
See also: Other Geeks@INDC

Just a simple question - 2

Without using your compiler, guess what will be the output of this code:

        static void Main(string[] args)
        {
            Sample<string, int> s = new Sample<string, int>("A", 0);

            Console.WriteLine(s.PropA + s.PropB);

            Console.ReadLine();
        }

    public class Sample<A, B>
    {
        public A PropA = null;
        public B PropB = null;

        public Sample(A a, B b)
        {
            PropA = a;
            PropB = b;
        }
    }

and why? 

Share this post: | | | |

Comments

Jimmy Chandra said:

Gut feeling says "A0" but I guess that would be wrong since it's a trick question. LoL.

Let see, you don't constraint A and B to any particular type or interface, so they might pass anything there.

If they pass DateTime, your code will blow up during compile time since DateTime is not a nullable type

Sample<DateTime, ...>

public DateTime PropA = null; //EEK!!! Not possible

changing your Sample class like so will make it work however...

   public class Sample<A, B>

   {

       public A PropA; //don't assign null here

       public B PropB; //don't assign null here

       public Sample(A a, B b)

       {

           PropA = a;

           PropB = b;

       }

   }

# April 16, 2008 11:17 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 
Are you human?:  


Enter the numbers above: