Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not "see" this enum extension method?

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);            
        }
    }
}
like image 798
Ben Aston Avatar asked Jul 20 '10 07:07

Ben Aston


People also ask

Can you add methods to enum?

You can use extension methods to add functionality specific to a particular enum type.

Can you extend enum Swift?

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.

What are the extension methods in dart?

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.


1 Answers

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>();
like image 88
Mark Byers Avatar answered Sep 19 '22 00:09

Mark Byers