The short answer is no.
Longer answer: in order for the class to support collection initializers, it needs to implement IEnumerable, and it needs to have an add method. For example:
public class MyClass<T,U> : IEnumerable<T> { public void Add(T t, U u) { } public IEnumerator<T> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
Then I can do this:
var mc = new MyClass<int, string> {{1, ""}, {2, ""}};
Therefore, using this, try to make it work for the attribute. (note, since the attributes do not support generics, I just hardcode them using strings for testing):
public class CollectionInitAttribute : Attribute, IEnumerable<string> { public void Add(string s1, string s2) { } public IEnumerator<string> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
And now, to check this out:
[CollectionInit{{"1","1"}}] public class MyClass { }
and this does not compile :( I'm not sure where the restriction is exactly, I guess that attributes are not created in the same way as a regular object, and therefore this is not supported. be curious if this could theoretically be supported by a future version of the language ... .
source share