Reputation: 426
I have a class that contains some values and an array, and I need elements in this array to have default values.
Like
class Object
{
public string OName { get; set;}
public string OType { get; set; }
public string Data { get; set; }
Object[] RelationList = new Object[5];
RelationList[0] = blabla;
RelationList[1] = blabla;
......
}
I need to set RelationList to some default values. Any body knows how to do that? Thanks.
Upvotes: 0
Views: 11359
Reputation: 8622
You can use object initialisers
Object[] RelationList = new[] {
new Object { OName = "abc", OType = "xyz", Data = "tetst" },
new Object { OName = "abc", OType = "xyz", Data = "tetst" },
new Object { OName = "abc", OType = "xyz", Data = "tetst" },
new Object { OName = "abc", OType = "xyz", Data = "tetst" }
};
Upvotes: 0
Reputation: 5313
Setting defaults can be done in a constructor for the object
class MyObject
{
public string OName { get; set; }
public string OType { get; set; }
public string Data { get; set; }
public Object[] RelationList = new Object[5];
public MyObject()
{
RelationList[0] = 1;
RelationList[1] = 2;
}
}
Depending on the circumstances, there are other mechanisms for setting these defaults (e.g. creating a new array in the constructor instead of at the declaration, passing them in on the constructor, etc.)
Upvotes: 0
Reputation: 3533
Initialize your properties in the constructor:
class Class1
{
public string OName { get; set;}
public string OType { get; set; }
public string Data { get; set; }
public object RelationList { get; set; }
public Class1()
{
// initialize your properties here
RelationList = new object[5];
RelationList[0] = blabla;
RelationList[1] = blabla;
}
}
Upvotes: 0
Reputation: 3962
You'll have to iterate through them.
E.g.
class Foo
{
private readonly object[] _relationList = new object[5];
public Foo(object defaultValue)
{
for (var i = 0; i < _relationList.Length; ++i) {
_relationList[i] = defaultValue;
}
}
}
Upvotes: 0
Reputation: 245479
Setting those defaults is the job of the constructor:
class SomeKindOfObject
{
public string OName { get; set; }
public string OType { get; set; }
public string Data { get; set; }
Object[] RelationList = new Object[5];
// Constructor
public SomeKindOfObject()
{
RelationList[0] = blabla;
}
}
Or, you could also just use an array initializer if you already have the objects laying around:
Object[] RelationList = new Object[] { blahblah, blahblah, blahblah, ect };
Upvotes: 4