Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Uncommented listing and added compilerAssert tests #543

Merged
merged 2 commits into from
Sep 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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; }
}
Loading