rafalio
rafalio

Reputation: 3946

Can I assign a static class to a variable?

My question is whether I can assign a static class to another variable (and of what type would that be) ?

Say I have

public static class AClassWithALongNameIDontWantTotType{
    public static bool methodA() { stuff }
}

and then I have

class B{

}

Can I make it so that inside of class B I can reassign this class to something with a shorter name, like:

SomeType a = AClassWithALongNameIDontWantTotType

and then be able to do

a.methodA()

?

I can get out a function by doing something like

Func<bool> a = AClassWithALongNameIDontWantTotType.methodA() 

but I would prefer to have the whole class.

Thanks!

Upvotes: 4

Views: 5372

Answers (2)

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68737

No you can't, because you can't have an instance of a static class. You can accomplish what you're looking for through Reflection or dynamic. To do this I created a DynamicObject to help:

class StaticMethodProvider : DynamicObject
{
    private Type ToWorkWith { get; set; }

    public StaticMethodProvider(Type toWorkWith)
    {
        ToWorkWith = toWorkWith;
    }

    public override bool TryInvokeMember(InvokeMemberBinder binder, 
        object[] args, out object result)
    {
        result = ToWorkWith.InvokeMember(binder.Name, BindingFlags.InvokeMethod, 
            null, null, null);
        return true;
    }
}

and then you'd be able to do

dynamic a = new StaticMethodProvider(
    typeof(AClassWithALongNameIDontWantTotType));
Console.WriteLine(a.methodA());

But then you wouldn't have intellisense and compile time safety. It's probably a bit of overkill.

Upvotes: 3

Mark H
Mark H

Reputation: 13907

If you want this purely for the purpose of avoiding typing long names, you can use an alias

using a = SomeNamespace.AClassWithALongNameIDontWantToType;

Upvotes: 11

Related Questions