jdk
jdk

Reputation: 139

How to set value for variable that refer to other class in constructor without parameter?

I have declared a list of variable including variable that refer to another class.

public class order {

    private int primaryid;
    private string desc;
    private int customerid;
    private Customer customer;

}

And I already create the get and set methods. How can I assign value to variable customer in constructor without parameter?

public order(){
   primaryid = 0;
   desc = string.empty;
   customerid = 0;
   customer = ?
}

Upvotes: 0

Views: 54

Answers (3)

Enigmativity
Enigmativity

Reputation: 117027

Other than setting customer to null or new Customer() then you can use one of two approaches:

Static variable:

void Main()
{
    order_helper.customer = new Customer();
    var order = new order();
}

public static class order_helper
{
    public static Customer customer;
}

public class order
{
    private int primaryid;
    private string desc;
    private int customerid;
    private Customer customer;

    public order()
    {
        primaryid = 0;
        desc = String.Empty;
        customerid = 0;
        customer = order_helper.customer;
    }
}

Or reflection:

    var field =
        typeof(order)
            .GetField("customer", BindingFlags.Instance | BindingFlags.NonPublic);

    var order = new order();
    field.SetValue(order, new Customer());

Upvotes: 0

Santhosh
Santhosh

Reputation: 729

Without any parameters you can only initialize the customer with a new instance.

customer = new Customer();

or if you are about to hard code the Customer properties, you can use

customer = new Customer{ *provide the initial values here* };

for eg, if customer has FirstName and LastName as its properties,

customer = new Customer{ FirstName = "someName" , LastName = "someLastName" };

Upvotes: 1

Dak
Dak

Reputation: 26

If you are just looking to instantiate a new customer try this:

public order(){
   primaryid = 0;
   desc = string.empty;
   customerid = 0;
   customer = new Customer();
}

Upvotes: 1

Related Questions