public
string
Name {
get
;
set
; }
int
price{
List<
> Extras{
Burger()
{
Extras =
new
>();
}
class
Pizza
price {
> Toppings {
Pizza()
Toppings =
cook()
return
"Cooking Pizza "
+ Name;
cook(
mins)
+ Name +
" for "
+mins+
" Mins"
To obtain the Type of an object statically at compile time, typeof method can be used.
var pizza =
Pizza();
Type t =
typeof
(Pizza);
Type t1 = pizza.GetType();
From a Type, several useful information can be obtained about an object, such as its name and assembly.
Console.WriteLine(t1.Name); //Pizza
Console.WriteLine(t1.Assembly); //Reflection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
To create an instance of a type, the method Activator.CreateInstance can be used. This method creates an instance of the specified type using the constructor that best matches the specified parameters.
Activator.CreateInstance can be used in 2 ways as described below: a. Creates an instance of the specified type using that type's default constructor.
var newpizza = (Pizza)Activator.CreateInstance(
(Pizza));
var newpizza1 = (Pizza)Activator.CreateInstance<pizza>();
PropertyInfo[] properties =
(Pizza).GetProperties();
PropertyInfo NameProperty =
null
PropertyInfo PriceProterty =
PropertyInfo ToppingProperty =
foreach
(var property
in
properties)
if
(property.Name.Equals(
"Name"
, StringComparison.CurrentCulture))
NameProperty = property;
else
"price"
PriceProterty = property;
"Toppings"
ToppingProperty = property;
NameProperty.SetValue(newpizza,
"MarlinPizza"
);
PriceProterty.SetValue(newpizza, 40);
ToppingProperty.SetValue(newpizza,
>() {
"cheese"
,
"meat"
});
var HawaiianPizza =
Name =
"HawaiianPizza"
price = 50,
>(){
};
var type = HawaiianPizza.GetType();
var property = type.GetProperty(
var value = property.GetValue(HawaiianPizza);
//value = "HawaiianPizza"
var method = type.GetMethod(
"cook"
Type[] { });
Type[] {
(
) });
var value = (
)method.Invoke(HawaiianPizza,
[] {
"5"
var BigBurger =
"BigBurger"
price = 100,
"Chips"
"Cheese"
PrintReceipt(HawaiianPizza);
PrintReceipt(BigBurger);
static
void
PrintReceipt(Object obj)
var type = obj.GetType();
(type.Name ==
"Pizza"
)
Console.WriteLine(
"Printing receipt for: "
+ type.GetProperty(
).GetValue(obj));
"Toppings: "
> toppings = (List<
>)type.GetProperty(
).GetValue(obj);
(var topping
toppings)
Console.WriteLine(topping);
"Price: "
"Burger"
"Extras: "
"Extras"
Congratulations on the guru award.
Great article.