Skip to content

Commit

Permalink
fix: Uncommented listing and added compilerAssert tests (#543)
Browse files Browse the repository at this point in the history
## Summary

Had to add an extra class that derived from PdaItem. The code now throws
the error

Fixes #541
  • Loading branch information
danOIntellitect authored Sep 12, 2023
1 parent 18464a4 commit 03a877d
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 5 deletions.
15 changes: 15 additions & 0 deletions src/Chapter12.Tests/Listing12.41.Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using AddisonWesley.Michaelis.EssentialCSharp.Shared.Tests;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_41.Tests;

[TestClass]
public class Listing12
{
[TestMethod]
public async Task CannotConvertTypes()
{
await CompilerAssert.CompileTestTargetFileAsync(
new string[] { "CS0030" });
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
using AddisonWesley.Michaelis.EssentialCSharp.Chapter08.Listing08_05;
using AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_11;

namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter12.Listing12_41;

public class Program
Expand All @@ -14,12 +11,57 @@ public static void Main()
Pair<Contact> contacts = new(contact1, contact2);

#region HIGHLIGHT
#if COMPILEERROR // EXCLUDE
// This gives an error: Cannot convert type ...
// But suppose it did not
// IPair<PdaItem> pdaPair = (IPair<PdaItem>) contacts;
IPair<PdaItem> pdaPair = (IPair<PdaItem>) contacts;
// This is perfectly legal, but not type-safe
// pair.First = new Address("123 Sesame Street");
pdaPair.First = new Address("123 Sesame Street");
#endif // COMPILEERROR // EXCLUDE
#endregion HIGHLIGHT
#endregion INCLUDE
}
}

public class Address : PdaItem
{
public Address(string address) : base(address)
{
}
}

public struct Pair<T> : IPair<T>
{
public Pair(T first, T second)
{
First = first;
Second = second;
}

public T First { get; set; }
public T Second { get; set; }
}

interface IPair<T>
{
T First { get; set; }
T Second { get; set; }
}

public class Contact : PdaItem
{
public Contact(string name)
: base(name)
{
}
}

public abstract class PdaItem
{
public PdaItem(string name)
{
Name = name;
}

public virtual string Name { get; set; }
}

0 comments on commit 03a877d

Please sign in to comment.