audin
audin

Reputation: 94

Explain System.Reflection.MemberInfo.Name property

I'm new to C#, so this is kind of hard for me to understand. System.Reflection.MemberInfo.Name property is stated as follows:

public abstract string Name { get; }

I understand that it is an auto-implemented property, but how the value of Name is set in the first place?

Upvotes: 1

Views: 1410

Answers (2)

Blorgbeard
Blorgbeard

Reputation: 103437

MemberInfo is an abstract class, which means it cannot be instantiated itself, only subclasses of it can be. That allows for some of its members to also be abstract, and the Name property is one.

Subclasses of MemberInfo must define a public property called Name with a public get accessor. How the accessor is defined is up to the subclass.

All you have to know is that any class which inherits from MemberInfo will provide you with a Name property that you can access.

Here's an example of two classes which inherit from an abstract class with an abstract property.

abstract class Base {
    public abstract string Name { get; }
}

class Derived1 : Base {
    public override string Name { get { return "Foobar"; } }
}

class Derived2 : Base {
    private string _name;
    public override string Name { get { return _name; } }
    public Derived2(string name) { _name = name; }
}

Upvotes: 0

usr
usr

Reputation: 171178

MemberInfo is a base class for others such as PropertyInfo. Derived classes override Name. You as a user of the reflection framework do not care that this is an abstract property. The Name is simply available for you to use.

Whether this is an auto-property or not is irrelevant and in fact you cannot find out. Auto-properties are a C# concept that disappears when compiled to IL.

The .NET Reflection system allows user code to derive their own classes from the typical reflection classes such as PropertyInfo. The framework provides default implementations. These default implementations (here: internal class RuntimePropertyInfo) provide an implementation for abstract members.

I'm not aware of anyone doing this or using this facility. It seems like a bad idea. I consider this to be a design bug in the .NET Framework.

Upvotes: 1

Related Questions