Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scope block of code?

Tags:

c#

.net

enums

If I need to reference a namespace explicitly to avoid conflicts with another namespace, how can that be done when you need to reference it several times within one block of code?

For example:

List<NamespaceA.SomeEnum> myobject = new List<NamespaceA.SomeEnum>()
{
  NamespaceA.SomeEnum.A,
  NamespaceA.SomeEnum.B,
  NamespaceA.SomeEnum.C,
  NamespaceA.SomeEnum.D,
  NamespaceA.SomeEnum.E,
}

Is there a way to shortcut/imply NamespaceA.SomeEnum in the parameter references?

like image 996
4thSpace Avatar asked Dec 21 '25 20:12

4thSpace


1 Answers

You can do

using ASomeEnum = NamespaceA.SomeEnum;

and then

List<ASomeEnum> myobject = new List<ASomeEnum>()
{
    ASomeEnum.A,
    ASomeEnum.B,
    ASomeEnum.C,
    ASomeEnum.D,
    ASomeEnum.E,
}

The using directive needs to be at the top level or within a namespace, but not within a type.


Another option is to move the method containing the offending code block to another file and to make the class partial.

This allows you to use different namespaces in the other file.

like image 88
Tobias Brandt Avatar answered Dec 23 '25 15:12

Tobias Brandt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!