Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Interface with static property or methods?

I need to define a static property or method in certain classes of my bussiness logic, to explicity determine which classes are cacheables in Session or Cache of ASP.NET service. I'm thinking, static property or method in the interface would be perfect, but C# 4.0 doesn't support this.

All a need is be able to evaluate in a generic manager which classes are cacheables and, if they are, at what level: session (user) or cache (application).

Now I'm trying with a empty interface with T parameter to evaluate, but, maybe exists a better approach?? Thanks.

public interface ICacheable<T>
{
}

public class Country : ICacheable<CacheApplication>
{
}

public class Department : ICacheable<CacheUser>
{
}

public class Gestor<T>
{
    // ...
    if (typeof(T) is ICacheable<CacheApplication>)
    {
    }
    // ...
}
like image 247
vladiastudillo Avatar asked Dec 09 '22 02:12

vladiastudillo


2 Answers

How about using a custom attribute? Your classes then would look something like this:

[Cacheable(Level = CacheLevels.Application)]
public class Country { }

[Cacheable(Level = CacheLevels.User)]
public class Department { }

You can read here on how to create your own custom attribute and then access its value by using reflection.

like image 178
Adi Lester Avatar answered Dec 25 '22 16:12

Adi Lester


You cant define static interfaces, for one thing, you cant make instances of static classes so you cant substitute them for others with the same base class.

You might be better off having a singleton instance of one class and using interfaces as normal. You could enforce one and one-only instance through a factory pattern too.

like image 31
IanNorton Avatar answered Dec 25 '22 16:12

IanNorton