-3

I'm trying to reference the type of a property on a class and I can't figure out the syntax:

List<IChildInfo<typeof(MappingModel.identifier)>> mappings;

Is this possible in .NET?

public class MappingModel
{
    public long identifier { get; set; }
}
Corey Alix
  • 2,694
  • 2
  • 27
  • 38

4 Answers4

2

The code you've presented won't work because the compiler has to create a specialized type for that particular list using the type you've specified.

The easiest way of fixing that would be to make a generic specialization "on the fly" ( or at run-time ).

example code:

// retrieve the property which type you want to get
var propertyInfo = typeof(MappingModel).GetProperty("identifier");
// get that property's type
Type propertyType = propertyInfo.PropertyType;

// now that you have a property type you can make a specialized generic type:
Type ichildtype = typeof(IChildInfo).MakeGenericType(propertyType);
// create a type definition for that particular list
Type listtype = typeof(List<>).MakeGenericType(ichildtype);
// create an instance of that list
Activator.CreateInstance(listtype);

Try this online

mrogal.ski
  • 5,828
  • 1
  • 21
  • 30
  • Appreciate the work but I was just looking for syntax sugar :) – Corey Alix Nov 09 '17 at 00:59
  • @CoreyAlix Yes, I thought about that but wanted to give some alternative way of achieving something similar. Which you can use to make it work a bit the way you wanted. Hope that it helped in any way :) – mrogal.ski Nov 09 '17 at 09:08
1

First examine the type of your surrounding class, then get its properties:

var p = typeof(MappingModel).GetProperties.FirstOrDefault(x => x.Name == "identifier");

Or also:

var p = typeof(MappingModel).GetProperty("identifier");

Now you can get the type of the property via PropertyType:

var t = p.PropertyType;

However as this is a runtime-information teher´s no way for the compiler to create an instance of a list of that type. You can create an interface that your type implements and then create a list of it:

var l = new List<IChildInfo<MyInterface>>();

where the type of MappingModel.identifier implements MyInterface. But this assumes IChildInfo to be co-variant:

interface IChildInfo<out T> { ... }
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
0

You need to use Reflection to that.

I'm not sure of what exactly you want to do but you can get all the property of a class doing :

typeof(MappingModel).GetProperties();

Then you can play with the properties.

JBO
  • 270
  • 1
  • 6
0

You can get the type of the property, but you won't be able to use it as a generic argument using normal syntax. You can use MethodInfo to invoke a method that would use mappings. This answer may prove to be helpful to you.

Dido
  • 520
  • 2
  • 7
  • 21