Why cannot I see this enum extension method? (I think I'm going crazy).
File1.cs
namespace Ns1
{
public enum Website : int
{
Website1 = 0,
Website2
}
}
File2.cs
using Ns1;
namespace Ns2
{
public class MyType : RequestHandler<Request, Response>
{
public override Response Handle(Request request, CRequest cRequest)
{
//does not compile, cannot "see" ToDictionary
var websites = Website.ToDictionary<int>();
return null;
}
}
//converts enum to dictionary of values
public static class EnumExtensions
{
public static IDictionary ToDictionary<TEnumValueType>(this Enum e)
{
if(typeof(TEnumValueType).FullName != Enum.GetUnderlyingType(e.GetType()).FullName) throw new ArgumentException("Invalid type specified.");
return Enum.GetValues(e.GetType())
.Cast<object>()
.ToDictionary(key => Enum.GetName(e.GetType(), key),
value => (TEnumValueType) value);
}
}
}
You can use extension methods to add functionality specific to a particular enum type.
We can extend the enum in two orthogonal directions: we can add new methods (or computed properties), or we can add new cases. Adding new methods won't break existing code. Adding a new case, however, will break any switch statement that doesn't have a default case.
Extension methods, introduced in Dart 2.7, are a way to add functionality to existing libraries. You might use extension methods without even knowing it. For example, when you use code completion in an IDE, it suggests extension methods alongside regular methods.
You are trying to call the extension method as a static method on the type rather than as an instance method on an object of that type. This usage of extension methods is not supported.
If you have an instance then the extension method is found:
Website website = Website.Website1;
var websites = website.ToDictionary<int>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With