15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Generic Methods ❘ 127<br />

match is taken. If an int is passed, then the method with the int parameter is selected. With any other<br />

parameter type, the compiler chooses the generic version of the method:<br />

public class MethodOverloads<br />

{<br />

public void Foo(T obj)<br />

{<br />

Console.WriteLine("Foo(T obj), obj type: {0}", obj.GetType().Name);<br />

}<br />

public void Foo(int x)<br />

{<br />

Console.WriteLine("Foo(int x)");<br />

}<br />

}<br />

public void Bar(T obj)<br />

{<br />

Foo(obj);<br />

}<br />

code snippet Specialization/Program.cs<br />

The Foo() method can now be invoked with any parameter type. The sample code passes an int <strong>and</strong> a<br />

string to the method:<br />

static void Main()<br />

{<br />

var test = new MethodOverloads();<br />

test.Foo(33);<br />

test.Foo("abc");<br />

}<br />

code snippet GenericMethods/Program.cs<br />

Running the program, you can see by the output that the method with the best match is taken:<br />

Foo(int x)<br />

Foo(T obj), obj type: String<br />

You need to be aware that the method invoked is defined during compile time <strong>and</strong> not runtime. This can be<br />

easily demonstrated by adding a generic Bar() method that invokes the Foo() method, passing the generic<br />

parameter value along:<br />

public class MethodOverloads<br />

{<br />

// ...<br />

public void Bar(T obj)<br />

{<br />

Foo(obj);<br />

}<br />

The Main() method is now changed to invoke the Bar() method passing an int value:<br />

static void Main()<br />

{<br />

var test = new MethodOverloads();<br />

test.Bar(44);<br />

From the output on the console you can see that the generic Foo() method was selected by the Bar()<br />

method <strong>and</strong> not the overload with the int parameter. The reason is that the compiler selects the method<br />

that is invoked by the Bar() method during compile time. Because the Bar() method defines a generic<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!