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;
}
}
}
Comments
Post a Comment