Instead of implicitly typing (var), how do I explicitly type static variables?

80 views Asked by At

Currently I implicitly typed eventOperation:

var eventOperation = EventOperations.Cancel;

But I explicitly type eventOperation so that I don't have to assign an arbitrary value before an if statement. Plus, I can't initialize variables within the if statement or have an uninitialized implicit typed variable.

Here's my definition of the static class:

public static class EventOperations
{
    ...
    public static OperationAuthorizationRequirement Cancel =
      new OperationAuthorizationRequirement { Name = Constants.CancelOperationName };
}

public class Constants
{
    ...
    public static readonly string CancelOperationName = "Cancel";
    ...
}
2

There are 2 answers

1
René Vogt On BEST ANSWER

EventOperations.Cancel obviously is of type OperationAuthorizationRequirement. So simply declare your variable as

OperationAuthorizationRequirement eventOperation = EventOperations.Cancel;
0
Bozhidar Stoyneff On

Another approach would be:

var eventOperation = null as EventOperations;

This way you can still declare your variable using var (implicitly) but specify the data type on the right, so the compiler can figure it out.

UPDATE

Your original post implies static variable declaration. I'm not sure if you using the term correctly here, but if you do, the situation slightly change...

As C# doesn't support static local variables, you need to declare the variable as static on a module level, i.e. not within a method but directly in the class.

public class SomeClass 
{
    private static EventOperations eventOperation = null;
    
    void SomeMethod()
    {
        if(true)
        {
            eventOperation = EventOperations.Cancel; // whatever value you set here, it'll be propagated to all the instances of some class.
        }
    }
}