11.07.2015 Views

Beginning C# 2008-from Novice-to-professional - A2Z Dotnet

Beginning C# 2008-from Novice-to-professional - A2Z Dotnet

Beginning C# 2008-from Novice-to-professional - A2Z Dotnet

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

310CHAPTER 11 ■ LEARNING ABOUT .NET GENERICSand properties that are not declared at the type level. Thus, the use of a .NET generics parameterwith an indexer or property will not work. In my opinion, that is a real <strong>C#</strong> language designflaw, because it means we need <strong>to</strong> write code like this:...using Devspace.Trader.Common;public interface IWorkbook : IDebug {IWorksheet GetSheet(string identifier);IWorksheetBase this[string identifier] { get; set; }string Identifier { get; }}In this modified declaration, the method GetSheet() acts like the get part of the indexer, butnotice where the .NET generics parameter BaseType is declared. The declaration is after themethod identifier and before the first bracket. In the case of IWorkbook, we use the method-level.NET generics parameter <strong>to</strong> allow the caller <strong>to</strong> determine the type of the worksheet instances.The implementation of IWorkbook has <strong>to</strong> do nothing other than perform the appropriate typecast. Method-level .NET generics parameters are great when you are dealing with mixed types,as in the case of IWorkbook.The code <strong>to</strong> retrieve a worksheet that previously needed a type cast is rewritten as follows:IWorkbook workbook;IWorksheet worksheet =workbook.GetSheet(WorksheetIdentifiers.Configuration);The type cast has not disappeared completely. It is done for us in the implementation ofthe GetSheet() method, as demonstrated by the following code.public IWorksheetGetSheet(string identifier) {lock (_worksheets) {IWorksheet retval = null;if (_worksheets.ContainsKey(identifier)) {retval =_worksheets[identifier] as IWorksheet;}else {retval = new Worksheet(identifier);_worksheets.Add(identifier, retval);}return retval;}}The bolded code shows that there is still a type cast, but the type cast is in the method,and it uses the .NET generics parameter declared at the method level.

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

Saved successfully!

Ooh no, something went wrong!