Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the public properties of a class in .NET core

Tags:

c#

.net-core

I notice that .NET core doesn't allow myObj.GetType().GetProperties() as no GetProperties method exists. Is there another way to obtain the properties of a class through reflection?

like image 279
user3791372 Avatar asked Nov 13 '16 22:11

user3791372


People also ask

What is GetProperties C#?

GetProperties() Returns all the public properties of the current Type.

Can we have private properties in C#?

Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property. The get and set accessors for the same property may have different access modifiers.

What is reflection C#?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.


2 Answers

It seems that myObj.GetType().GetProperties() IS valid. I just had to bring in System.Reflection by using System.Reflection.

like image 169
user3791372 Avatar answered Nov 11 '22 12:11

user3791372


Just to sum up to anyone else, just adding using System.Reflection to the top of the page is not enough. You will have to add the System.Reflection.TypeExtensions NuGet package as described in the question comments.

PM> Install-Package System.Reflection.TypeExtensions -Version 4.3.0

like image 40
Moslem Ben Dhaou Avatar answered Nov 11 '22 14:11

Moslem Ben Dhaou