-2

Im trying to get object keys from an object in C#. How to do that? For example: object Test has keys named Ticket, and Hash. How to get that?

internal class Test
    {
        public string Ticket { get; internal set; } = "TICKECIOR";
        public object Hash {get; internal set; } = null;
    }

I want it to output Ticket and hash. It needs to be compatible with other objects.

I try to use it like this:

List<string> l = new List<string>();
var obj = new Test {Ticket = "test val"};
// I need to get the keys name and add them to list.
l.Add("key name");
ajdocik
  • 1
  • 2
  • 4
    The names of properties in C# aren't really "keys" in the same sense they are in JavaScript. While you can use reflection APIs to get the names, doing so is usually best left for certain rare scenarios. Could you edit your question to include your use case and example code of how the Test object is used? – Joe Sewell Sep 04 '20 at 16:55
  • Does this answer your question? [Get properties and values from unknown object](https://stackoverflow.com/questions/4144778/get-properties-and-values-from-unknown-object) – madreflection Sep 04 '20 at 17:00
  • Your edit doesn't really answer the question of *why* you are trying to do this. Why do you need to have a list of strings containing the names of the properties? – Joe Sewell Sep 04 '20 at 17:06
  • If you need key value pairs, use a dictionary which allows very fast access by key. – ckuri Sep 04 '20 at 18:52

1 Answers1

2

You can do something like below

typeof(Test).GetProperties().Select(x => x.Name).ToList();
Sowmyadhar Gourishetty
  • 1,843
  • 1
  • 8
  • 15