HI WELCOME TO KANSIRIS

Reflection to Get All List Property Names and Values in C#

Leave a Comment
By using Reflection PropertiesInfo we can easily get object list property names and values based on our requirements.

Following is the simple code snippet to get all the property names and values of an object in c# using reflection.

C# Code


Type type = user.GetType();
PropertyInfo[] props = type.GetProperties();
string str = "{";
foreach (var prop in props)
{
str+= (prop.Name+":"+  prop.GetValue(user))+",";
}
return str.Remove(str.Length-1)+"}";

If you want complete example to get all the properties and values of an object write the code like as shown following.

C# Code


using System;
using System.Collections.Generic;
using System.Reflection;

namespace SampleConsoleApp
{
class Program
{
static void Main(string[] args)
{
List<userdetails> items = new List<userdetails>();
items.Add(new userdetails { userid = 1, username = "suresh", location = "chennai" });
items.Add(new userdetails { userid = 2, username = "rohini", location = "guntur" });
items.Add(new userdetails { userid = 3, username = "praveen", location = "bangalore" });
items.Add(new userdetails { userid = 4, username = "sateesh", location = "vizag" });
items.Add(new userdetails { userid = 5, username = "madhav", location = "nagpur" });
items.Add(new userdetails { userid = 6, username = "honey", location = "nagpur" });
string strmsg = string.Empty;
foreach (var user in items)
{
strmsg = GetPropertyValues(user);
Console.WriteLine(strmsg);
}
Console.ReadLine();
}
private static string GetPropertyValues(userdetails user)
{
Type type = user.GetType();
PropertyInfo[] props = type.GetProperties();
string str = "{";
foreach (var prop in props)
{
str+= (prop.Name+":"+  prop.GetValue(user))+",";
}
return str.Remove(str.Length-1)+"}";
}
}
class userdetails
{
public int userid { getset; }
public string username { getset; }
public string location { getset; }
}
}


If you observe above code we added namespace “System.Reflection” to get properties and values of an object using PropertyInfo property
.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.