Home > DeveloperSection > Forums > How to get a private property name with value
Samuel Fernandes
Samuel Fernandes

Total Post:156

Points:1096
Posted on    December-16-2013 12:31 AM

 C# C# 
Ratings:


 1 Reply(s)
 819  View(s)
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; }

}



Pravesh Singh

Total Post:411

Points:2881
Posted on    December-16-2013 12:50 AM

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();

      }

   }

}


Don't want to miss updates? Please click the below button!

Follow MindStick