Emil
Emil

Reputation: 6893

Virtual function with static class?

if I define under the same namespace 2 functions in 2 different classes as below

namespace Cache
{ 
    /// <summary>
    /// Cache manager interface
    /// </summary>
    public interface ICacheManager
    {
        T Get<T>(string key);
    }
}

namespace  Cache
{
    class CacheManager : ICacheManager
    {
        public virtual T Get<T>(string key)
        {
            return (T)Cache[key];
        }
    }
}

namespace Cache
{
    public static class CacheExtensions
    {
        public static T Get<T>(this ICacheManager cacheManager, string key, Func<T> acquire)
        {
            return Get(cacheManager, key, 60, acquire);
        }
    }
}

If i create an instance

ICacheManager _cacheManager;

and when I call the _cacheManager.Get(key,()=>myfunction()) method with parameters like that it will redirect to the CacheExtensions class rather than CachManager class although ICacheManager was inherited from it? Could you kindly explain how does it work overriding a function with shared? How is that getting related?

Upvotes: 0

Views: 119

Answers (1)

Alex Lebedev
Alex Lebedev

Reputation: 609

Basically, extension method is not a function overriding. To be more accurate - overriding applicable for virtual(abstract) functions. In your case - it more close to overloading.

Basically, extensions is just a just a sugar, for not to have Action1(Action2(Action3(Action4(obj)))), but extensions will be translated to this.

https://msdn.microsoft.com/en-us//library/bb383977.aspx

If you need to call instance method from extension - use reference passed under 'this' keyword.

Upvotes: 1

Related Questions