How to access “statically” instance members of types?

  • A+

I would like to access "statically" (i.e. in compile time) given instance members of types (of course to retrieve static properties of them, not actual values or something like this).


interface IFoo {   int X { get; } } 

I would like to access X directly to retrieve what is known in compile time, for example:


Reflection is runtime, I am asking about compile-time.


No, there is no C# operator to refer to members in a compile-time type-safe way like this. It's a feature that is frequently requested, but really difficult to design well. The nameof operator introduced in C# 6 manages to skirt around most of the design issues, while satisfying most use cases.

Even if the supposed infoof operator did exist, it's unlikely that there's be a way of accessing specific properties from it (such as the name of the return type of the property) at compile time.

If the "compile-time" part is important to you for the sake of safety rather than in order to actually evaluate the name at compile-time, there are ways that could work. For example:

public static class TypeHelpers<TInput> {     public static Type GetReturnType<TOutput>(Func<TInput, TOutput> func) =>         typeof(TOutput); } 


Type returnType = TypeHelpers<IFoo>.GetReturnType(foo => foo.X); Console.WriteLine(returnType.FullName); // System.Int32 

That would be better than having to find the member at execution time, but it's still requesting the type name at execution time.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: