C# Corner
Tech
News
Videos
Forums
Trainings
Books
Events
More
Interviews
Jobs
Live
Learn
Career
Members
Blogs
Challenges
Certifications
Bounties
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Create Object to Generic or Unknown Class
WhatsApp
Sakthikumar Thanavel
10y
54.8
k
0
0
25
Blog
Sample.zip
Here I will go to explain about how to create the object to generic or unknown class. This situation we will get in the most of the situation. Mostly this will useful to develop the independent component development. So we will see through the sample. Create three different classes like below code:
public
class
Employee
{
public
string
Name
{
get
;
set
;
}
public
string
Address
{
get
;
set
;
}
}
public
class
Student
{
public
string
Name
{
get
;
set
;
}
public
string
Department
{
get
;
set
;
}
public
Student(
string
name,
string
department)
{
this
.Name = name;
this
.Department = department;
}
}
These two classes are totally different type and the constructor also different. Here I will go to create the object to these two classes by using one generic method. Generally we can’t
able to create the object to generic type like:
T obj=
new
T();
It will throw the exception. But we will get the type of generic type by using
typeof
operator. So here I go to use the typeof operator. If we know the type, we will easily create the object by using
Activator
class located in the
System
namespace. The below code show you to how to do this.
T GetObject < T > (
params
object
[] lstArgument)
{
return
(T) Activator.CreateInstance(
typeof
(T), lstArgument);
}
So by using this method we will create the object to any class. Here I will create the object to both class like this.
// Create object with default parameter.
Employee emp = GetObject < Employee > ();
emp.Name =
"Sakthikumar"
;
emp.Address =
"Chennai"
;
Console.WriteLine(
"Employee Detail"
);
Console.WriteLine(
"----------------"
);
Console.WriteLine(
"Name : "
+ emp.Name);
Console.WriteLine(
"Address : "
+ emp.Address);
// Create object with argumented parameter.
Student student = GetObject < Student > (
"Sakthikumar"
,
"MCA"
);;
Console.WriteLine(
"Student Detail"
);
Console.WriteLine(
"----------------"
);
Console.WriteLine(
"Name : "
+ emp.Name);
Console.WriteLine(
"Department : "
+ emp.Address);
Please feel free if you have any doubt regarding this.
People also reading
Membership not found