Mikołaj Kowal
Mikołaj Kowal

Reputation: 21

Using static method from generic class

I have problem as above. My code:

public abstract class BaseFactory<T> where T: class
{
    protected static dbModelContainer context = new dbModelContainer();

    public static int UpdateDataBase_static()
    {
        return context.SaveChanges();
    }
 }

and my question is how can I call

BaseFactory.UpdateDataBase_static();

instead of:

BaseFactory<SomeClass>.UpdateDataBase_static();

Any ideas?

Upvotes: 0

Views: 1048

Answers (4)

Sir Rufo
Sir Rufo

Reputation: 19096

To call BaseFactory.UpdateDataBase_static(); you need a class BaseFactory. Inherite the generic BaseFactory<T> from it.

public abstract class BaseFactory
{
    protected static dbModelContainer context = new dbModelContainer();

    public static int UpdateDataBase_static()
    {
        return context.SaveChanges();
    }
 }

public abstract class BaseFactory<T>:BaseFactory where T: class
{
    ....
}

Upvotes: 2

Jon Hanna
Jon Hanna

Reputation: 113242

You can't, because there is no such method. The closest is to have a non-generic base that the generic class inherits from. Then you can have a method there that doesn't depend on the parameterising type.

Upvotes: 2

recursive
recursive

Reputation: 86074

It's not possible to do exactly what you're asking, but since the method doesn't use T at all, you can just use BaseFactory<object>.UpdateDataBase_static(); without specifying any particular class.

But as an editorial comment, in general a method in a generic class that never uses the generic parameter probably shouldn't be there.

Upvotes: 0

Servy
Servy

Reputation: 203821

You don't.

You always need to supply the generic type arguments when accessing a class, even though you aren't using that type argument in your method. Since you don't actually use the generic type in the method it means you could move that method out of that class, and into one that isn't generic, but for as long as it's in that class you'll need to supply the generic argument.

Upvotes: 1

Related Questions