5

I have a class as like the following

namespace Foo.Bar
{
    public static class ParentClass
    {
      public const string myValue = "Can get this value";

      public static class ChildClass
      {
        public const string myChildValue = "I want to get this value";
      }
     }
}

I can get the myValue using powershell,

[System.Reflection.Assembly]::LoadWithPartialName("Foo.Bar")
$parentValue = [Foo.Bar.ParentClass]::myValue

But I'm unable to get the class within the class myChildValue. Can anyone help?

Thought it might be something like below but $childValue is always empty.

[System.Reflection.Assembly]::LoadWithPartialName("Foo.Bar")
$childValue = [Foo.Bar.ParentClass.ChildClass]::myChildValue

1 Answer 1

12

It's [Foo.Bar.ParentClass+ChildClass]. On PowerShell 3 tab completion will tell you as much. Furthermore, you can use Add-Type to compile and load the code directly:

C:\Users\Joey> add-type 'namespace Foo.Bar
>> {
>>     public static class ParentClass
>>     {
>>       public const string myValue = "Can get this value";
>>
>>       public static class ChildClass
>>       {
>>         public const string myChildValue = "I want to get this value";
>>       }
>>      }
>> }'
>>
C:\Users\Joey> [Foo.Bar.ParentClass+ChildClass]::myChildValue
I want to get this value

No need to fiddle around with the C# compiler and [Assembly]::LoadWithPartialName.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, extra point for answering so fast. Is that what + sign for, so if there was a class underneath the childclass would it me Foo.Bar.ParentClass+ChildClass+ChildOfChildClass
The + is from the internal name of that class. C# uses the dot . for both namespace separation and nested classes, but .NET itself doesn't. This becomes apparent when you use reflection to access types as well (and is also documented there, about halfway down the page). So yes, nested nested classes would use + as well.
Thank you for the link and explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.