Jeb50
Jeb50

Reputation: 7037

How to populate a List of Class of string?

A dumb C# question, if I have this code:

public class singleString
{
        public string ss { get; set; }
}
List<singleString> manyString = new List<singleString>();

How can I populate manyString to something like {"1", "2", "3"} ?

Upvotes: 1

Views: 223

Answers (2)

Shreevardhan
Shreevardhan

Reputation: 12641

Define implicit conversion operator

public class singleString {
    public string ss { get; set; }

    public static implicit operator singleString(string s) {
        return new singleString { ss = s };
    }
}

Then, use List initializer

var manyString = new List<singleString>() { "1", "2", "3" };

You can also initialize an array using the same operator

singleString[] manyString = { "1", "2", "3" };

Upvotes: 5

M. Adeel Khalid
M. Adeel Khalid

Reputation: 1796

You can do something like this:

List<singleString> manyString = new List<singleString>()
{
    new singleString(){ss="1"},
    new singleString(){ss="2"},
    new singleString(){ss="3"},
};

Upvotes: 6

Related Questions