2

I have an object that has a List<String> as a member. I tried adding items to this list in the following way:

$myObject.MyList.Add("News")
$myObject.MyList.Add("FAQ")
$myObject.MyList.Add("Events")

But when I check:

$myObject.MyList.Count

It returns 0. Is there a different way I should be doing this?

Snippit from my source code:

    [Personalizable(PersonalizationScope.Shared), WebBrowsable(false)]
    public List<String> SelectedTabs
    {
        get;
        set;
    }
2
  • Have you checked that $myObject.MyList is definitely a List and not null etc. and that it is implimented such that it gives the same list each time it's accessed. Not for example: public MyList {get{return new List<string>();}}//Always returns a new list Commented Dec 15, 2011 at 22:10
  • That smells like a sharepoint webpart - there's something else going on here, probably to do with the serialization of the property value. What's your context? Commented Dec 16, 2011 at 1:46

2 Answers 2

5

I'm not a developer but maybe this is what you're looking for:

PS> $list = New-Object System.Collections.Generic.List[System.String]
PS> $list.Add("News")
PS> $list.Add("FAQ")
PS> $list.Add("Events")
PS> $list
News
FAQ
Events    

PS> $list.Count
3
Sign up to request clarification or add additional context in comments.

Comments

3

Works for me:

$source =@"
using System.Collections.Generic;
public class MyClass {
    public List<string> MyList;
    public MyClass(){
    MyList = new List<string>();
    }
}

"@

Add-Type -TypeDefinition $source -Language CSharpVersion3

$myObject = new-object MyClass

$myObject.MyList.Add("test");

$myObject.MyList.Count

2 Comments

Would it make a difference that I am using [reflection.assembly]::Load("MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=13da1371f01433e6e") instead of Add-Type?
@AbeMiessler - It shouldn't. Do you have sample code for you assembly?

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.