Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I Reference Const Fields From a Nested Struct Without Referencing the Containing Class?

Tags:

c#

Consider the following case

public class SomethingWithAReallyReallyAnnoyinglyLongName{
    public struct Names
    {
        public const string SomeConstant = "Hello";
        public const string SomeOtherConstant = "World";
    }
}

Is there a way of referencing SomethingWithAReallyReallyAnnoyinglyLongName.Names.SomeConstant without having to reference SomethingWithAReallyReallyAnnoyinglyLongName, when outside of the SomethingWithAReallyReallyAnnoyinglyLongName context?

// Won't work "Struct Name is not valid at this point."
var names = SomethingWithAReallyReallyAnnoyinglyLongName.Names;
SomeFunction(names.SomeConstant, names.SomeOtherConstant);

// Won't work "Cannot access static constant..."
var names = new SomethingWithAReallyReallyAnnoyinglyLongName.Names();
SomeFunction(names.SomeConstant, names.SomeOtherConstant);

The long class name is auto-generated, so I can't change that, but I could probably change anything about the Names struct (make it a class, change the consts to not be const, etc.).

Any ideas?

like image 966
Daryl Avatar asked Mar 20 '26 08:03

Daryl


1 Answers

Well, in the files consuming the class you can do this:

using SwarralnNames = SomethingWithAReallyReallyAnnoyingLongName.Names;

Then you can type SwarralnNames.SomeConstant

Not ideal, since you need to apply this using in each file that wants the appropriate 'shortcut' name, but it can really help clean up multiple references in the same file if you can't control the original name.

like image 101
Dan Bryant Avatar answered Mar 23 '26 19:03

Dan Bryant



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!