Reputation: 857
I have two classes and a method like this:
public class Class1
{
public int Id { get; set; }
public string Name { get; set; }
public Class2 Params { get; set; }
}
public class Class2
{
public string Param1 { get; set; }
public string Param2 { get; set; }
public string Param3 { get; set; }
}
private Class1 GetData(SqlDataReader reader)
{
var model = new Class1
{
Id = Convert.ToInt32(reader["ID"]),
Name = reader["Name"].ToString(),
Class2.
};
}
Why I cannot see the properties of Class2
?
Upvotes: 3
Views: 126
Reputation: 8098
Because when you use Class2.
you're referencing the class itself, not an instance of the class.
You have to either declare Class2
as static
or, in your case, create an instance of it:
private Class1 GetData(SqlDataReader reader)
{
var model = new Class1
{
Id = Convert.ToInt32(reader["ID"]),
Name = reader["Name"].ToString(),
Params = new Class2 { Param1 = "foo", Param2 = "bar", Param3 = "other" }
};
}
Upvotes: 4
Reputation: 1678
The Params property of Class1 is never assigned to anything and so will always be null.
Also, the property accessor in Class1 is Params, so it should be...
private Class1 GetData(SqlDataReader reader)
{
var model = new Class1
{
Id = Convert.ToInt32(reader["ID"]),
Name = reader["Name"].ToString(),
Params = new Class2() { Param1 = "foo", Param2 = "bar" }
};
}
Upvotes: 0
Reputation: 33815
Dave is correct. The easiest way to do this with your code is as follows
private Class1 GetData(SqlDataReader reader)
{
var model = new Class1
{
Id = Convert.ToInt32(reader["ID"]),
Name = reader["Name"].ToString(),
Params = new Class2()
};
}
Upvotes: 0
Reputation: 5551
Class1 doesn't have a property called Class2. You called the property of type "Class2" on Class1, "Params". So you'd reference it like:
private Class1 GetData(SqlDataReader reader)
{
var model = new Class1
{
Id = Convert.ToInt32(reader["ID"]),
Name = reader["Name"].ToString(),
Params = new Class2 {
Param1 = ...
}
};
}
Upvotes: 2
Reputation: 21887
You need to create an instance
of Class2
. Your Params
object of Class1
needs to be initialized like so:
var model = new Class1
{
Id = Convert.ToInt32(reader["ID"]),
Name = reader["Name"].ToString(),
};
model.Params = new Class2();
model.Params.Param1 = "param1";
Upvotes: 4