Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing nested object properties

Tags:

c#

I have a class called employee which has a field called insurance which is of type insurance like this

public class Employee
{
    public string Name;
    public Insurance Insurance;
}

I have another class called Insurance

public class Insurance
{
    public int PolicyId;
    public String PolicyName;
} 

Now in the main program i want to do something like

var myEmployee = new Employee();
myEmployee.Name = "Jhon";
myEmployee.Insurance.PolicyId = 123 ;
myEmployee.Insurance.PolicyName = "Life Time" ;

C# is complaining and i know how to fix it by creating a instance of the Insurance class.

My question is can i somehow assign the values for the fields in the way i want to do it in the main program using like

**

myEmployee.Insurance.PolicyId = 123 ;
myEmployee.Insurance.PolicyName = "Life Time" ;

** I tried

 public class Employee
    {

        public Employee()
        {
            Insurance Insurance = new Insurance();
        }

        public String Name;
        public Insurance Insurance;



        public class Insurance
        {
            public int PolicyId;
            public String PolicyName;
        } 
    }

In the main method when i try

class Program
    {
        static void Main(string[] args)
        {
            var joe = new Employee();
            joe.Name = "Joe";
            joe.Insurance.

        }

I get this error-

Error 2 Ambiguity between 'ConsoleApplication1.Employee.Insurance' and 'ConsoleApplication1.Employee.Insurance' c:\users\lenovo\documents\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs 15 17 ConsoleApplication1

like image 579
jhon.smith Avatar asked Aug 08 '13 18:08

jhon.smith


People also ask

How to initialize nested object in c#?

An object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas. Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and an expression or an object initializer or collection initializer.

How to initialize objects in JS?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation). An object initializer is a comma-delimited list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ( {} ).

How do you initialize an object in C#?

The compiler processes object initializers by first accessing the parameterless instance constructor and then processing the member initializations. Therefore, if the parameterless constructor is declared as private in the class, object initializers that require public access will fail.

Why we initialize object in c#?

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements.


2 Answers

You could instantiate Insurance in Employee's constructor so it is done automatically for you. You could provide it default values to ensure it is understood that is not yet defined to be valid when accessed later on.

public class Employee
{
    Insurance Insurance { get; set; }

    public Employee()
    {
        this.Insurance = new Insurance() { PolicyId = -1 };
    }
}

public class Insurance
{
    public int PolicyId { get; set; }
    public string PolicyName { get; set; }
}

Or to keep the classes nested:

public class Employee
{
    Insurance InsurancePolicy { get; set; }

    public Employee()
    {
        this.InsurancePolicy = new Insurance() { PolicyId = -1 };
    }
    public class Insurance
    {
        public int PolicyId { get; set; }
        public string PolicyName { get; set; }
    }
}
like image 126
bland Avatar answered Oct 24 '22 00:10

bland


Without requiring changes to your Employee class, you could use object initializers:

var myEmployee = new Employee 
{
    Name = "Jhon",
    Insurance = new Insurance
    {
        PolicyId = 123,
        PolicyName = "Life Time"
    }
};

Alternatively, and maybe preferably, you can have the Employee class create a new instance of Insurance either in its constructor (as in the other answers), or one other option would be to do it in the Insurance property getter itself, so it's instantiated only if you use it. Here's an example of the latter:

class Employee 
{
    private Insurance insurance;

    public Insurance Insurance
    {
        get
        {
            if (insurance == null)
            {
                insurance = new Insurance();
            }
            return insurance;
        }
    }
}

Lastly, I would suggest that you don't build classes that have all public fields unless you really know that's what you want. Instead, I would consider using properties over fields. I have incorporated other's suggestions into the following code, and provided my own:

public class Employee
{
    public Employee() 
    {
        this.Insurance = new Insurance();
    }

    // Perhaps another constructor for the name?
    public Employee(string name)
        : this()
    {
        this.Name = name;
    }

    public string Name { get; set; }
    public Insurance Insurance { get; private set; }
}

public class Insurance
{
    public int PolicyId { get; set; }
    public string PolicyName { get; set; }
}
like image 12
Cᴏʀʏ Avatar answered Oct 23 '22 23:10

Cᴏʀʏ