-1

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";
    ...
}
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
CCSJ
  • 833
  • 1
  • 6
  • 8
  • `But I explicitly type eventOperation so that I don't have to assign an arbitrary value before an if statement.` Please show an example of an if statement that you are trying to build. – mjwills Aug 31 '17 at 10:08
  • 1
    It is unclear exactly what your problem is. Please specify. – Maritim Aug 31 '17 at 10:10
  • I'm not sure to get the question, but var is only made that type declaration is automatic regarding the type of data you're assigning. I guess... just use Visual Studio tools to figure out which kind of data you're using ? – Kinxil Aug 31 '17 at 10:11

2 Answers2

3

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

OperationAuthorizationRequirement eventOperation = EventOperations.Cancel;
René Vogt
  • 43,056
  • 14
  • 77
  • 99
  • This works. Its just that I misspelled it and it was giving me a namespace error without giving me a proper fix so I thought its something else. Thanks! – CCSJ Sep 01 '17 at 01:34
0

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.
        }
    }
}
Community
  • 1
  • 1
Bozhidar Stoyneff
  • 3,576
  • 1
  • 18
  • 28