8protons
8protons

Reputation: 3959

Why set a property value of an interface?

In the following code for a custom HttpClient, I found a method take takes an interface and writes to it as if it was an object with properties:

public async Task<T> GetAsync<T>(ICacheContext cacheContext = null) {
    try {
        T result = default(T);

        // check if value is cached
        if (cacheContext != null) {
            result = await GetResultFromCache<T>(cacheContext);        
            if (result != null) {
                cacheContext.IsDataFromCache = true;
                return result;
            }
        }

I'm a bit confused by cacheContext.IsDataFromCache = true;. Why would you set the property of an interface? Isn't that something you'd do to the object implementation of said interface?

Upvotes: 0

Views: 358

Answers (2)

The Lemon
The Lemon

Reputation: 1389

By referencing the interface instead of the concrete class, you can easily swap out implementations of your interface without having to change every method that references your object. In the code example, if there were three implementations of ICacheContext that all need the method, using the interface allows them to all use the same method. Otherwise you would need to create three GetAsync methods with a different signature for each implementation.

Another reason you would use the Interface in your method signature instead of the base class, is to enforce good coding practices - if the method only needs the ICacheContext properties of your base class, using the interface stops you from using other properties/methods of your implementation (maybe CacheContextImplementation.cs also handles logging or configs or something that you don't want handled in the 'GetAsync' method), restricting yourself to the interface forces you to be more OOP friendly.

Also, technically, the code isn't setting the property of the interface. It's setting the property of the implementation, using the mask of the interface.

Hope this helps, and makes sense

Upvotes: 1

chinshuu
chinshuu

Reputation: 61

Probably it receives an instance that implements ICacheContext as regards to polymorphism of OOP

for instance

ICacheContext cacheCtx = new CacheContextImpl()  // Class which implements ICacheContext

Upvotes: 1

Related Questions