How to get a private property name with value

Total Post:159

Points:1117
C# 
C#
 1456  View(s)
Ratings:
Rate this:

Is there anyway I can get my private property of a class from another class? Here what I have tried.

class Program
{
    static void Main(string[] args)
    {
        Sample aSample = new Sample();
        //Is there anyway to access that Name private property here?
    }
}
class Sample
{
    private string Name { get; set; }
}

  1. Post:412

    Points:2888
    Re: How to get a private property name with value

    Here I have tried with Reflection namespace and PropertyInfo class.

    Please try it if you want property name with it's value. But in this case your property should be public. It shows all property names and their values.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Reflection;
    namespace PropertiesImpConsoleApp
    {
      class Student
      {
         //Declare variables
         string firstname;
         string lastname;
        //Define property for the variables
         public string FirstName
         {
             get
             {
                 return firstname;
             }
             set
             {
                 firstname = value;
             }
         }
         public string LastName
         {
             get
             {
                 return lastname;
             }
             set
             {
                 lastname = value;
             }
         }
      }
      class MyMain
      {
          public static void Main(string[] args)
          {
              Student aStudent = new Student();
              Console.WriteLine("Enter First Name");
              aStudent.FirstName = Console.ReadLine();
              Console.WriteLine("Enter LastName");
              aStudent.LastName = Console.ReadLine();
             //And to get the properties names you can do like this
              Dictionary<string, string> aDictionary = new Dictionary<string, string>();
              PropertyInfo[] allproperties = aStudent.GetType().GetProperties().ToArray();
              foreach (var aProp in allproperties)
              {
                  aDictionary.Add(aProp.Name, aProp.GetValue(aStudent, null).ToString());
              }
              foreach (KeyValuePair<string, string> pair in aDictionary)
              {
                  Console.WriteLine("{0}, {1}",
                  pair.Key,
                  pair.Value);
              }
              Console.ReadLine();
          }
       }
    }

      Modified On Apr-03-2018 06:33:08 AM

Answer