Using Object and Collection Initialize


Another tiresome programming task is constructing a new object and then assigning values to the properties, look at the example where I will be constructing object and then initializing its properties.

using System;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //creating new StudentInfo object
            StudentInfo studentInfo = new StudentInfo();
 
            //set the property values
            studentInfo.ID = 1;
            studentInfo.Name = "Abhimanyu";
            studentInfo.Address = "Bokaro, India";
            studentInfo.Course = "M.Tech(IT)";
 
            //process the student information
            ProcessStudentInfo(studentInfo);
        }
 
        private static void ProcessStudentInfo(StudentInfo studentInfo)
        {
            //TODO
        }
    }
 
    //StudentInfo class
    public class StudentInfo
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Course { set; get; }
    }
}
 
We must go through three stages to create a StudentInfo object and pass it to the ProcessStudentInfo method: create the object, set the parameter values, and then call the method. Fortunately, we can use the object initialize feature, which allows us to do everything in one go, look at the example given below:

using System;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //creating new StudentInfo object
            ProcessStudentInfo(new StudentInfo
            {
                ID = 1, Name = "Abhimanyu", Address = "Bokaro, India", Course = "M.Tech(IT)"
            });
        }
 
        private static void ProcessStudentInfo(StudentInfo studentInfo)
        {
            //TODO
        }
    }
 
    //StudentInfo class
    public class StudentInfo
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Course { set; get; }
    }
}
 
The braces ({}) after the call to the StudentInfo constructor are the initialize. We can supply values to the parameters as part of the construction process. The result is an instance of the StudentInfo class that we can pass directly to the ProcessStudentInfo method, which means we don't need to use a local variable to refer to the StudentInfo while we initialize it.

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples