Setting Property Value using Reflection [duplicate] - c#

This question already has an answer here:
Can I set a property value with Reflection?
(1 answer)
Closed 6 years ago.
How do I set my property value from array via reflection in C#?
public class Employee
{
public string Name { get; set; }
public int ID { get; set; }
public void SetValues(string[] items)
{
}
}
I need to use SetValues method to set property values from items array.

Considering you said you Need to use SetValues(string[] items) {...}, and that you'd have an Employee object such as:
Employee emp = new Employee();
I believe you're looking for:
string[] values = new string[] {"someName", "someID"};
typeof(Employee).GetMethod("SetValues").Invoke(emp, new object[]{ values });
Now SetValues would have to convert (in its body) "someID" to int with something like:
ID = int.Parse(items[1]);

Related

Method to return a List<T> from a List<OwnStruct>, where List<T> then contains only one Property of all OwnStructs in List (C#) [duplicate]

This question already has answers here:
convert a list of objects from one type to another using lambda expression
(14 answers)
Closed 1 year ago.
I'm struggling with this a little.
I have a List<HeadStruc_Table> within my program.
The Class HeadStruct looks like following:
public partial class HeadStruct_Table : IComparable<HeadStruct_Table>
{
public string colName { get; set; }
public string colName_edit { get; set; }
public string alternativeNames { get; set; }
public int Table_ID { get; set; }
public bool colFound { get; set; }
public CheckBox cBox { get; set; }
I don't know how to create a method with parameters (List<HeadStruct_Table>, HeadStruct_Table.colName) that then returns a List<TypeOf(HeadStruct_Table.colName)> containing only the values of colName in this specific case.
Of course it should work for the bool and even CheckBox property as well.
As parameter HeadStruct_Table.colName doesn't work right now, as it is declared as just public and not public static, do i have to declare it as public static or is there any other chance to pass the specific property. Maybe by using a predicate?
That's the way it maybe could look like later?
public static IList<T> getList<T>(List<HeadStruct_Table> list, Func<HeadStruct_Table, T> getType)
{
var newList = new List<T>();
I just don't know how to get the special property and then, in the method, just read out those values. I wouldn't like to work with a string as parameter if it works without.
Anyone who has an idea?
That is my first question. I'm open for any advice to improve asking a question in here. Thank You.
LINQ's Enumerable.Select method already does what you want:
var newList = list.Select(x => x.colName).ToList();

Why and when should I use "this" to access methods from base class during inheritance in c#? [duplicate]

This question already has answers here:
When do you use the "this" keyword? [closed]
(31 answers)
Closed 3 years ago.
Noobie here, but I was wondering why and when would I need to use "this" keyword to access the Promote method in GoldenCustomer when I can already access it since GoldenCustomer is derived from the base class Customer which already has this method? Saw "this" being used in an online course but could't help but wonder.
Edit:
No my question isnt a duplicate because the other question doesnt answer when and if it is necessary to use "this" during inheritance.
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
customer.Promote();
GoldCustomer goldCustomer = new GoldCustomer();
goldCustomer.OfferVoucher();
}
}
public class GoldCustomer : Customer{
public void OfferVoucher(){
this.Promote(); //why is this used here?
}
}
public class Customer{
public int Id { get; set; }
public string Name { get; set; }
public void Promote(){
int rating = CalculateRating(excludeOrders: true);
if (rating == 0)
System.Console.WriteLine("Promoted to level 1");
else
System.Console.WriteLine("Promoted to level 2");
}
private int CalculateRating(bool excludeOrders){
return 0;
}
}
The most common uses is when a variable in a method/function has the same name as another class-level variable.
In this case, using the this keyword will tell the compiler that you're referring to the class's variable.
For example:
public class Customer
{
public string Name { get; set; }
Public Customer (string Name, string Id)
{
this.Name = Name; // "this.Name" is class's Name while "Name" is the function's parameter.
}
}
MSDN Doc for other uses and further reading
Also, a small side-note: ID should always be stored as a string since int has the maximum value of 2147483648, and ID's are treated as a string anyway (you never use math-related functions on it like Id++ or Id = Id * 2 for example).
I'm obviously referring to state-issued IDs like "6480255197" and not "1", "2" and so on.

How to clone List<T> item correctly? [duplicate]

This question already has answers here:
Deep cloning objects
(58 answers)
Closed 6 years ago.
I have problem with cloning List item.
Class Item
{
String Name;
Int Age;
}
Than I have a List<>
List<Item> Items = new List<Items>();
now if i do this action
Item val= Items[i];
Now if I change val's age,it will also change Items[i] age.
How to clone item from List,so when changing values in cloned item,values wouldn't change in List?
This if for examle,but my class im bigger,it contains more than 20 values.
Item it = new Item();
it.Name = Items[i].Name;
it.Age = Items[i].Age;
Create a new object of class Item and initialize it's member variables using list item. Also for this either set member variables Name and Age as public or expose them through public properties.
A Class is a reference type. By using Item val= Items[i]; you're just assigning the reference to Items[i] to val, so when you amend one you amend the other.
You need to create a new Item and populate its properties from the original Item[i]:
var val = new Item()
{
Name = Items[i].Name,
Age = Items[i].Age
};
It's possible you may need to set the correct access on your Item class as well:
public class Item
{
public string Name { get; set; }
public int Age { get; set; }
}

How can I dynamically select the property of an object in an object list I want to modify the value of [duplicate]

This question already has an answer here:
Can I set a property value with Reflection?
(1 answer)
Closed 8 years ago.
I have a list of a class object
lets say the class is structured like this
class DataEntity
{
public string col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
}
so the list would be
List<DataEntity> list = new List<DataEntity>
So here is my issue I need to loop through list and modify the value of a specific property..but I don't know what property need to be modified until run time.
so lets say there is a Method that converts the list and the property name to be modified is passed in as a string value
public List<DataEntity> Convert (List<DataEntity> list, string propertyName, string appendedValue)
{
}
SO my question is how can I loop though that list and for the propertyName entered append the appendedValue to that properties value
I know I can get the proeprties values using reflection like this
Type type = dataEntity.GetType();
foreach (PropertyInfo pi in type.GetProperties())
{
}
but I'm not sure how that can be leveraged to target a specific property for appending at runtime.
you should use something like this :
PropertyInfo propertyInfo;
foreach (YourClass C in list)
{
propertyInfo = C.GetType().GetProperty(propertyName);
propertyInfo.SetValue(C, Convert.ChangeType(appendedValue, propertyInfo.PropertyType), null);
}
return list;
For more information you can check these links :Setting a property, Getting property value

Update a class property using reflection and the name of the property as a string [duplicate]

This question already has answers here:
Set object property using reflection
(10 answers)
Closed 9 years ago.
I have a sample class
public class sampleClass
{
public string givenName { get; set; }
public string familyName { get; set; }
}
and a set of values for that class contained in IDictionary<string, object> dataModel. I can use reflection to iterate through the dataModel and use the dataModel key to get the value.
I would like to do something like:
void UpdateValues(IDictionary<string, object> dataModel)
{
Type sourceType = typeof(sampleClass);
foreach (PropertyInfo propInfo in (sourceType.GetProperties()))
{
if (dataModel.ContainsKey(propInfo.Name))
{
// set propInfo value here
propInfo.Value = dataModel[propInfo.Name];
}
}
}
But i have no idea how to do the line
propInfo.Value = dataModel[propInfo.Name];
Help! Thanks !!
you need an instance of the sampleClass to set the property on and then you can use the SetValue function to do that:
propInfo.SetValue(yourinstance, dataModel[propInfo.Name], null);
see this URL: http://msdn.microsoft.com/en-us/library/axt1ctd9.aspx
propInfo.SetValue(sampleClass, dataModel[propInfo.Name], null)

Categories